/**
 * JH 数据可视化仪表板 JavaScript - 个性化增强版
 * 处理数据可视化、用户交互、个性化配置和API调用
 */

class JHDashboard {
    constructor() {
        this.apiBaseUrl = 'http://localhost:8000/api/jh';
        this.charts = {};
        this.currentFilters = {};
        this.currentPage = 1;
        this.pageSize = 33; // 默认33条数据
        this.totalPages = 1;
        this.totalJobs = 0;
        this.isLoading = false;
        this.sortable = null;
        
        // 图表模态框管理
        this.modalChart = null; // 模态框中的图表实例
        this.currentModalChartId = null; // 当前模态框显示的图表ID
        
        // 图表展开状态管理
        this.expandedCharts = new Set(); // 存储展开的图表ID
        
        // 新增：当前页职位与当前查看职位索引/详情
        this.currentJobs = [];
        this.currentJobIndex = -1;
        this.currentJobDetail = null;
        
        // 注册Chart.js插件
        this.registerChartPlugins();
        
        // 个性化配置
        this.userPreferences = {
            theme: 'light',
            chartConfigs: {
                jobTypeChart: { type: 'doughnut', dimension: 'job_type' },
                locationChart: { type: 'bar', dimension: 'location' },
                salaryChart: { type: 'bar', dimension: 'salary_range' },
                timeChart: { type: 'line', dimension: 'daily' },
                skillsChart: { type: 'horizontalBar', dimension: 'top_skills' },
                companyChart: { type: 'bar', dimension: 'job_count' }
            },
            layout: []
        };
        
        this.init();
    }
    
    // 注册Chart.js插件
    registerChartPlugins() {
        try {
            // 注册缩放插件
            if (typeof window.zoomPlugin !== 'undefined') {
                Chart.register(window.zoomPlugin);
            } else if (typeof window.ChartZoom !== 'undefined') {
                Chart.register(window.ChartZoom);
            } else {
                console.warn('Chart.js zoom plugin not found, zoom functionality will be disabled');
            }
        } catch (error) {
            console.warn('Failed to register Chart.js plugins:', error);
        }
    }
    
    async init() {
        console.log('初始化JH个性化数据仪表板...');
        
        // 首先尝试API调用获取真实数据
        try {
            await this.loadOverviewData();
            await this.loadJobsData();
            await this.loadChartsData();
        } catch (error) {
            console.warn('API调用失败，使用Mock数据:', error);
            this.displayMockJobsTable();
            this.loadMockChartsData();
        }
        
        // 初始化其他组件
        this.initializeFilters();
        this.initializeCharts();
        this.initializePersonalization();
        this.initializeDragAndDrop();
        this.loadUserPreferences();
        this.initializeModal();
        this.initializeResizeHandler();
        this.initJobDetailModal();
        
        console.log('✅ JH数据仪表板初始化完成');
    }
    
    // 修改：加载概览数据
    async loadOverviewData() {
        try {
            const response = await fetch(`${this.apiBaseUrl}/overview`);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            this.displayOverviewStats(data);
            console.log('✅ 概览数据加载成功');
        } catch (error) {
            console.error('概览数据加载失败:', error);
            throw error;
        }
    }
    
    // 修改：加载职位数据
    async loadJobsData() {
        try {
            // 显示加载状态
            this.showLoadingState();
            
            // 获取第一页数据来测试API
            const params = new URLSearchParams({
                page: this.currentPage,
                page_size: this.pageSize,
                ...this.buildQueryParams()
            });
            
            const response = await fetch(`${this.apiBaseUrl}/jobs?${params}`);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            
            // 立即显示职位数据，不需要等待筛选
            this.displayJobsTable(data.items || []);
            this.updatePagination(data);
            this.totalJobs = data.total_items || 0;
            
            // 隐藏加载状态
            this.hideLoadingState();
            
            console.log(`✅ 职位数据加载成功: ${this.totalJobs} 条数据`);
            
            // 更新统计信息
            this.updateJobStats(data.items || []);
            
        } catch (error) {
            console.error('职位数据加载失败:', error);
            this.hideLoadingState();
            this.showErrorState('职位数据加载失败，请稍后重试');
            throw error;
        }
    }
    
    // 修改：加载图表数据
    async loadChartsData() {
        const chartIds = ['jobTypeChart', 'locationChart', 'salaryChart', 'timeChart', 'skillsChart', 'companyChart'];
        const promises = chartIds.map(chartId => this.createChart(chartId));
        
        try {
            await Promise.all(promises);
            console.log('✅ 所有图表数据加载成功');
        } catch (error) {
            console.error('图表数据加载失败:', error);
            throw error;
        }
    }
    
    // 新增：显示加载状态
    showLoadingState() {
        const tbody = document.getElementById('jobsTableBody');
        if (tbody) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="9" class="loading-state">
                        <div class="loading-spinner">
                            <i class="fas fa-spinner fa-spin"></i>
                            <span>正在加载职位数据...</span>
                        </div>
                    </td>
                </tr>
            `;
        }
    }
    
    // 新增：隐藏加载状态
    hideLoadingState() {
        // 加载状态会被实际数据替换，这里可以做一些清理工作
    }
    
    // 新增：显示错误状态
    showErrorState(message) {
        const tbody = document.getElementById('jobsTableBody');
        if (tbody) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="9" class="error-state">
                        <div class="error-message">
                            <i class="fas fa-exclamation-triangle"></i>
                            <span>${message}</span>
                            <button class="btn btn-primary btn-sm" onclick="jhDashboard.loadJobsData()">
                                <i class="fas fa-redo"></i> 重新加载
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }
    }
    
    // 新增：更新职位统计
    updateJobStats(jobs) {
        if (!Array.isArray(jobs)) return;
        
        // 更新总数显示
        const totalElement = document.querySelector('.overview-card .card-value');
        if (totalElement) {
            totalElement.textContent = this.totalJobs.toLocaleString();
        }
        
        // 计算其他统计信息
        const remoteJobs = jobs.filter(job => job.job_work_from_home == 1).length;
        const avgSalary = jobs.reduce((sum, job) => sum + (job.salary_year_avg || 0), 0) / jobs.length;
        
        // 更新其他统计卡片
        this.updateStatCard('remote-jobs', remoteJobs);
        this.updateStatCard('avg-salary', `$${Math.round(avgSalary).toLocaleString()}`);
    }
    
    // 新增：更新统计卡片
    updateStatCard(cardId, value) {
        const card = document.getElementById(cardId);
        if (card) {
            const valueElement = card.querySelector('.card-value');
            if (valueElement) {
                valueElement.textContent = value;
            }
        }
    }
    
    // 新增：获取匹配度等级样式类
    getMatchScoreClass(score) {
        if (score >= 0.9) return 'match-excellent';
        if (score >= 0.8) return 'match-high';
        if (score >= 0.6) return 'match-medium';
        if (score >= 0.4) return 'match-low';
        return 'match-very-low';
    }
    
    // 新增：初始化筛选器
    initializeFilters() {
        // 筛选器初始化逻辑
        console.log('初始化筛选器');
    }
    
    // 新增：初始化图表
    initializeCharts() {
        // 图表初始化逻辑
        console.log('初始化图表');
    }
    
    // 新增：初始化个性化设置
    initializePersonalization() {
        // 个性化设置初始化逻辑
        console.log('初始化个性化设置');
    }
    
    // 新增：加载Mock图表数据
    loadMockChartsData() {
        const chartIds = ['jobTypeChart', 'locationChart', 'salaryChart', 'timeChart', 'skillsChart', 'companyChart'];
        chartIds.forEach(chartId => {
            const config = this.userPreferences.chartConfigs[chartId];
            const mockData = this.getMockChartData(chartId, config.dimension, false);
            this.updateChart(chartId, mockData, config.type, config.dimension);
        });
    }
    
    // 新增：构建查询参数
    buildQueryParams() {
        const params = {};
            
        // 添加筛选条件
        if (this.currentFilters.search) {
            params.search = this.currentFilters.search;
        }
        if (this.currentFilters.job_title) {
            params.job_title = this.currentFilters.job_title;
        }
        if (this.currentFilters.company_name) {
            params.company_name = this.currentFilters.company_name;
        }
        if (this.currentFilters.job_location) {
            params.job_location = this.currentFilters.job_location;
        }
        if (this.currentFilters.job_country) {
            params.job_country = this.currentFilters.job_country;
        }
        if (this.currentFilters.job_schedule_type) {
            params.job_schedule_type = this.currentFilters.job_schedule_type;
        }
        if (this.currentFilters.salary_min) {
            params.salary_min = this.currentFilters.salary_min;
        }
        if (this.currentFilters.salary_max) {
            params.salary_max = this.currentFilters.salary_max;
        }
        if (this.currentFilters.work_from_home !== undefined) {
            params.work_from_home = this.currentFilters.work_from_home;
        }
        if (this.currentFilters.skills && this.currentFilters.skills.length > 0) {
            params.skills = this.currentFilters.skills.join(',');
        }
        
        return params;
    }
    
    // 新增：显示概览统计
    displayOverviewStats(stats) {
        // 更新概览卡片
        const updateStat = (id, value, formatter = null) => {
            const element = document.getElementById(id);
            if (element) {
                element.textContent = formatter ? formatter(value) : value;
            }
        };
        
        updateStat('totalJobs', stats.total_jobs || 0, val => val.toLocaleString());
        updateStat('avgSalary', stats.avg_salary || 0, val => `¥${Math.round(val).toLocaleString()}`);
        updateStat('remoteJobs', stats.remote_jobs || 0, val => val.toLocaleString());
        updateStat('totalCompanies', stats.total_companies || 0, val => val.toLocaleString());
        
        // 更新百分比显示
        const remotePercentage = stats.remote_percentage || 0;
        updateStat('remotePercentage', remotePercentage, val => `${val.toFixed(1)}%`);
    }
    
    // 修改：更新职位表格函数
    async updateJobsTable() {
        try {
            // 使用真实API
            const params = new URLSearchParams({
                page: this.currentPage,
                page_size: this.pageSize,
                ...this.buildQueryParams()
            });
            
            const response = await fetch(`${this.apiBaseUrl}/jobs?${params}`);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            this.displayJobsTable(data.items || []);
            this.updatePagination(data);
            this.totalJobs = data.total_items || 0;
            
        } catch (error) {
            console.error('更新职位表格失败:', error);
            // 回退到Mock数据
            this.displayMockJobsTable();
        }
    }
    
    // 修改：创建图表函数 - 删除重复函数，使用后面的版本
    
    // 加载用户偏好设置
    loadUserPreferences() {
        const saved = localStorage.getItem('jh_dashboard_preferences');
        if (saved) {
            try {
                const preferences = JSON.parse(saved);
                this.userPreferences = { ...this.userPreferences, ...preferences };
            } catch (error) {
                console.warn('加载用户偏好设置失败:', error);
            }
        }
    }
    
    // 保存用户偏好设置
    saveUserPreferences() {
        try {
            localStorage.setItem('jh_dashboard_preferences', JSON.stringify(this.userPreferences));
        } catch (error) {
            console.warn('保存用户偏好设置失败:', error);
        }
    }
    
    // 主题切换功能
    applyTheme(theme) {
        const body = document.body;
        const themeToggle = document.getElementById('themeToggle');
        
        // 移除所有主题类
        body.classList.remove('light-theme', 'dark-theme');
        
        if (theme === 'auto') {
            // 自动检测系统主题
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            theme = prefersDark ? 'dark' : 'light';
        }
        
        body.classList.add(`${theme}-theme`);
        this.userPreferences.theme = theme;
        
        // 更新主题切换按钮图标
        if (themeToggle) {
            const icon = themeToggle.querySelector('i');
            icon.className = theme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
        }
        
        // 更新配置面板中的主题按钮状态
        this.updateThemeButtons();
        
        this.saveUserPreferences();
    }
    
    // 更新主题按钮状态
    updateThemeButtons() {
        const themeButtons = document.querySelectorAll('.theme-btn');
        themeButtons.forEach(btn => {
            btn.classList.remove('active');
            if (btn.dataset.theme === this.userPreferences.theme) {
                btn.classList.add('active');
            }
        });
    }
    
    // 初始化拖拽功能
    initializeDragAndDrop() {
        const chartsGrid = document.getElementById('chartsGrid');
        if (chartsGrid && typeof Sortable !== 'undefined') {
            this.sortable = Sortable.create(chartsGrid, {
                handle: '.drag-handle',
                animation: 150,
                ghostClass: 'sortable-ghost',
                chosenClass: 'sortable-chosen',
                onEnd: (evt) => {
                    this.saveLayout();
                }
            });
        }
    }
    
    // 保存布局
    saveLayout() {
        const chartsGrid = document.getElementById('chartsGrid');
        if (chartsGrid) {
            const layout = Array.from(chartsGrid.children).map(card => {
                return card.dataset.chartId;
            });
            this.userPreferences.layout = layout;
            this.saveUserPreferences();
        }
    }
    
    // 重置布局
    resetLayout() {
        this.userPreferences.layout = [];
        this.saveUserPreferences();
        
        // 重新排列图表顺序
        const chartsGrid = document.getElementById('chartsGrid');
        const defaultOrder = ['jobTypeChart', 'locationChart', 'salaryChart', 'timeChart', 'skillsChart', 'companyChart'];
        
        defaultOrder.forEach(chartId => {
            const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
            if (chartCard) {
                chartsGrid.appendChild(chartCard);
            }
        });
        
        this.showNotification('布局已重置为默认设置');
    }
    
    // 初始化配置面板
    initializeConfigPanel() {
        this.generateChartConfigList();
        this.updateThemeButtons();
        
        // 绑定主题按钮事件
        const themeButtons = document.querySelectorAll('.theme-btn');
        themeButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                this.applyTheme(btn.dataset.theme);
            });
        });
    }
    
    // 生成图表配置列表
    generateChartConfigList() {
        const configList = document.getElementById('chartConfigList');
        if (!configList) return;
        
        const chartConfigs = [
            { id: 'jobTypeChart', name: '职位类型分布', icon: 'fa-chart-pie' },
            { id: 'locationChart', name: '地区职位分布', icon: 'fa-chart-bar' },
            { id: 'salaryChart', name: '薪资分布', icon: 'fa-chart-area' },
            { id: 'timeChart', name: '时间趋势', icon: 'fa-chart-line' },
            { id: 'skillsChart', name: '技能需求', icon: 'fa-fire' },
            { id: 'companyChart', name: '公司排行', icon: 'fa-trophy' }
        ];
        
        configList.innerHTML = chartConfigs.map(config => `
            <div class="chart-config-item">
                <h5><i class="fas ${config.icon}"></i> ${config.name}</h5>
                <div style="display: flex; gap: 0.5rem; margin-top: 0.5rem;">
                    <button class="btn btn-sm" onclick="dashboard.hideChart('${config.id}')">
                        <i class="fas fa-eye-slash"></i> 隐藏
                    </button>
                    <button class="btn btn-sm" onclick="dashboard.showChart('${config.id}')">
                        <i class="fas fa-eye"></i> 显示
                    </button>
                </div>
            </div>
        `).join('');
    }
    
    // 显示/隐藏图表
    hideChart(chartId) {
        const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
        if (chartCard) {
            chartCard.style.display = 'none';
        }
    }
    
    showChart(chartId) {
        const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
        if (chartCard) {
            chartCard.style.display = 'block';
        }
    }
    
    // 切换图表类型
    changeChartType(chartId, newType) {
        this.userPreferences.chartConfigs[chartId].type = newType;
        this.saveUserPreferences();
        this.refreshChart(chartId);
        this.showNotification('图表类型已更新');
    }
    
    // 切换图表维度
    changeDimension(chartId, newDimension) {
        this.userPreferences.chartConfigs[chartId].dimension = newDimension;
        this.saveUserPreferences();
        this.refreshChart(chartId);
        this.showNotification('图表维度已更新');
    }
    
    showLoading() {
        const overlay = document.getElementById('loadingOverlay');
        if (overlay) {
            overlay.classList.add('active');
        }
    }
    
    hideLoading() {
        const overlay = document.getElementById('loadingOverlay');
        if (overlay) {
            overlay.classList.remove('active');
        }
    }
    
    showError(message) {
        this.showNotification(message, 'error');
    }
    
    showNotification(message, type = 'success') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${type === 'error' ? '#ef4444' : '#10b981'};
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            z-index: 10000;
            animation: slideIn 0.3s ease;
        `;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        // 3秒后自动移除
            setTimeout(() => {
            notification.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
            }, 3000);
    }
    
    async loadOverviewStats() {
        try {
            const response = await fetch(`${this.apiBaseUrl}/stats`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const stats = await response.json();
            this.displayOverviewStats(stats);
            
        } catch (error) {
            console.error('加载概览统计失败:', error);
            this.displayMockOverviewStats();
        }
    }
    
    displayOverviewStats(stats) {
        const elements = {
            totalJobs: document.getElementById('totalJobs'),
            totalCompanies: document.getElementById('totalCompanies'),
            topLocation: document.getElementById('topLocation'),
            topLocationLabel: document.getElementById('topLocationLabel'),
            avgSalary: document.getElementById('avgSalary')
        };
        
        if (elements.totalJobs) elements.totalJobs.textContent = this.formatNumber(stats.total_jobs || 0);
        if (elements.totalCompanies) elements.totalCompanies.textContent = this.formatNumber(stats.total_companies || 0);
        if (elements.topLocation) elements.topLocation.textContent = stats.top_location || 'N/A';
        if (elements.topLocationLabel) elements.topLocationLabel.textContent = stats.top_location || '北京';
        if (elements.avgSalary) elements.avgSalary.textContent = stats.avg_salary ? '$' + this.formatNumber(Math.round(stats.avg_salary)) : 'N/A';
    }
    
    displayMockOverviewStats() {
        const mockStats = {
            total_jobs: 22003,
            total_companies: 3247,
            top_location: '北京',
            avg_salary: 123286
        };
        this.displayOverviewStats(mockStats);
    }
    
    formatNumber(num) {
        return num.toLocaleString();
    }
    
    async initializeCharts() {
        const chartIds = ['jobTypeChart', 'locationChart', 'salaryChart', 'timeChart', 'skillsChart', 'companyChart'];
        
        for (const chartId of chartIds) {
            await this.createChart(chartId);
        }
        
        // 应用保存的布局
        this.applyLayout();
        
        // 同步所有图表控件状态
        this.syncAllChartControls();
    }
    
    // 应用保存的布局
    applyLayout() {
        if (this.userPreferences.layout && this.userPreferences.layout.length > 0) {
            const chartsGrid = document.getElementById('chartsGrid');
            this.userPreferences.layout.forEach(chartId => {
                const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
                if (chartCard) {
                    chartsGrid.appendChild(chartCard);
                }
            });
        }
    }
    
    // 初始化标签筛选器
    async initializeTagFilters() {
        try {
            // 获取筛选选项数据
            const filterData = await this.getFilterOptions();
            
            // 生成工作类型标签
            this.generateScheduleTags(filterData.scheduleTypes);
            
            // 生成国家标签
            this.generateCountryTags(filterData.countries);
            
            // 绑定标签点击事件
            this.bindTagEvents();
            
        } catch (error) {
            console.error('初始化标签筛选器失败:', error);
        }
    }
    
    // 获取筛选选项数据
    async getFilterOptions() {
        try {
            const response = await fetch(`${this.apiBaseUrl}/filter-options`);
            if (!response.ok) {
                throw new Error('Failed to fetch filter options');
            }
            return await response.json();
        } catch (error) {
            console.error('获取筛选选项失败:', error);
            // 返回模拟数据
            return {
                scheduleTypes: ['Full-time', 'Part-time', 'Contractor', 'Temp work', 'Internship'],
                countries: ['United States', 'Germany', 'Canada', 'United Kingdom', 'Australia', 'Mexico', 'France', 'Brazil', 'Netherlands', 'Denmark']
            };
        }
    }
    
    // 生成工作类型标签
    generateScheduleTags(scheduleTypes) {
        const container = document.getElementById('scheduleTagGroup');
        if (!container) return;
        
        container.innerHTML = '';
        
        scheduleTypes.forEach(type => {
            const tag = document.createElement('div');
            tag.className = 'filter-tag';
            tag.dataset.filter = 'job_schedule_type';
            tag.dataset.value = type;
            
            const icon = this.getScheduleIcon(type);
            tag.innerHTML = `
                <span>${type}</span>
                <i class="fas ${icon}"></i>
            `;
            
            container.appendChild(tag);
        });
    }
    
    // 生成国家标签
    generateCountryTags(countries) {
        const container = document.getElementById('countryTagGroup');
        if (!container) return;
        
        container.innerHTML = '';
        
        countries.forEach(country => {
            const tag = document.createElement('div');
            tag.className = 'filter-tag';
            tag.dataset.filter = 'job_country';
            tag.dataset.value = country;
            
            const flag = this.getCountryFlag(country);
            tag.innerHTML = `
                <span>${country}</span>
                ${flag}
            `;
            
            container.appendChild(tag);
        });
    }
    
    // 获取工作类型图标
    getScheduleIcon(type) {
        const icons = {
            'Full-time': 'fa-clock',
            'Part-time': 'fa-clock-o',
            'Contractor': 'fa-handshake',
            'Temp work': 'fa-calendar-alt',
            'Internship': 'fa-graduation-cap',
            'Contract': 'fa-handshake'
        };
        return icons[type] || 'fa-briefcase';
    }
    
    // 获取国家旗帜或图标
    getCountryFlag(country) {
        const flags = {
            'United States': '🇺🇸',
            'Germany': '🇩🇪',
            'Canada': '🇨🇦',
            'United Kingdom': '🇬🇧',
            'Australia': '🇦🇺',
            'Mexico': '🇲🇽',
            'France': '🇫🇷',
            'Brazil': '🇧🇷',
            'Netherlands': '🇳🇱',
            'Denmark': '🇩🇰'
        };
        return flags[country] || '<i class="fas fa-globe"></i>';
    }
    
    // 绑定标签事件
    bindTagEvents() {
        const filterTags = document.querySelectorAll('.filter-tag');
        filterTags.forEach(tag => {
            tag.addEventListener('click', () => {
                this.toggleFilterTag(tag);
            });
        });
    }
    
    // 重新绑定所有筛选事件（包括静态的远程工作标签）
    rebindFilterEvents() {
        // 重新绑定所有筛选标签事件
        this.bindTagEvents();
    }
    
    // 切换筛选标签状态
    toggleFilterTag(tag) {
        const isActive = tag.classList.contains('active');
        const filterField = tag.dataset.filter;
        const filterValue = tag.dataset.value;
        
        if (isActive) {
            // 移除筛选
            tag.classList.remove('active');
            delete this.currentFilters[filterField];
        } else {
            // 添加筛选（先清除同类型的其他筛选）
            const sameTypeActiveTags = document.querySelectorAll(`.filter-tag[data-filter="${filterField}"].active`);
            sameTypeActiveTags.forEach(activeTag => {
                activeTag.classList.remove('active');
            });
            
            tag.classList.add('active');
            this.currentFilters[filterField] = filterValue;
        }
        
        // 更新活跃筛选显示
        this.updateActiveFilters();
        
        // 重新加载数据
        this.currentPage = 1;
        this.loadJobsTable();
    }
    
    async createChart(chartId) {
        try {
            const config = this.userPreferences.chartConfigs[chartId];
            const data = await this.getChartData(chartId, config.dimension);
            const chartConfig = this.getChartConfig(config.type, data, chartId);
            
            const canvas = document.getElementById(chartId);
            if (!canvas) return;
            
            // 销毁现有图表
            if (this.charts[chartId]) {
                this.charts[chartId].destroy();
            }
            
            // 创建新图表
            const ctx = canvas.getContext('2d');
            this.charts[chartId] = new Chart(ctx, chartConfig);
            
            // 更新图表标题
            this.updateChartTitle(chartId, config.dimension);
            
            // 同步表头控件状态
            this.syncChartControls(chartId, config.type, config.dimension);
            
        } catch (error) {
            console.error(`创建图表 ${chartId} 失败:`, error);
        }
    }
    
    // 更新图表标题
    updateChartTitle(chartId, dimension) {
        const titleElement = document.querySelector(`[data-chart-id="${chartId}"] .chart-title`);
        if (!titleElement) return;
        
        const dimensionNames = {
            // 职位类型图
            job_type: '职位类型分布',
            schedule_type: '工作类型分布',
            remote_type: '远程类型分布',
            
            // 地区图
            location: '地区职位分布',
            country: '国家职位分布',
            city: '城市职位分布',
            
            // 薪资图
            salary_range: '薪资范围分布',
            avg_by_type: '各职位类型平均薪资',
            avg_by_location: '各地区平均薪资',
            
            // 时间图
            daily: '每日发布趋势',
            weekly: '每周发布趋势',
            monthly: '每月发布趋势',
            
            // 技能图
            top_skills: '热门技能需求',
            skills_by_type: '各职位类型技能需求',
            emerging_skills: '新兴技能趋势',
            
            // 公司图
            job_count: '招聘职位数量排行',
            avg_salary: '平均薪资排行',
            growth_rate: '增长率排行'
        };
        
        titleElement.textContent = dimensionNames[dimension] || titleElement.textContent;
    }
    
    async refreshChart(chartId, expanded = null) {
        console.log(`刷新图表: ${chartId}`);
        
        // 如果没有明确指定展开状态，使用当前状态
        if (expanded === null) {
            expanded = this.expandedCharts.has(chartId);
        }
        
        try {
            const config = this.userPreferences.chartConfigs[chartId];
            if (!config) {
                console.warn(`图表配置不存在: ${chartId}`);
                return;
            }
            
            const data = await this.getChartData(chartId, config.dimension, expanded);
            this.updateChart(chartId, data, config.type, config.dimension);
            
        } catch (error) {
            console.error(`刷新图表失败 (${chartId}):`, error);
            this.showNotification(`刷新图表失败: ${chartId}`, 'error');
        }
    }
    
    async getChartData(chartId, dimension, expanded = false) {
        try {
            // 添加expanded参数到API调用
            const url = `${this.apiBaseUrl}/chart-data/${chartId}?dimension=${dimension}&expanded=${expanded}`;
            const response = await fetch(url);
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            return data;
            
        } catch (error) {
            console.error(`获取图表数据失败 (${chartId}):`, error);
            return this.getMockChartData(chartId, dimension, expanded);
        }
    }
    
    getMockChartData(chartId, dimension, expanded = false) {
        const mockData = {
            jobTypeChart: {
                job_type: { 
                    labels: expanded ? 
                        ['Data Scientist', 'Data Engineer', 'Data Analyst', 'Software Engineer', 'Machine Learning Engineer', 'Business Analyst', 'Product Manager', 'DevOps Engineer', 'Full Stack Developer', 'Backend Developer', 'Frontend Developer', 'Mobile Developer'] : 
                        ['Data Scientist', 'Data Engineer', 'Data Analyst', 'Software Engineer', 'Machine Learning Engineer'], 
                    values: expanded ? 
                        [3245, 2891, 4123, 3567, 1821, 1456, 1234, 1123, 987, 876, 765, 654] : 
                        [3245, 2891, 4123, 3567, 1821] 
                },
                schedule_type: { 
                    labels: expanded ? 
                        ['Full-time', 'Part-time', 'Contractor', 'Internship', 'Freelance', 'Temporary'] : 
                        ['Full-time', 'Part-time', 'Contractor', 'Internship'], 
                    values: expanded ? 
                        [12847, 1234, 987, 779, 567, 345] : 
                        [12847, 1234, 987, 779] 
                },
                remote_type: { 
                    labels: expanded ? 
                        ['Fully Remote', 'Hybrid', 'On-site', 'Remote-friendly', 'Flexible'] : 
                        ['Fully Remote', 'Hybrid', 'On-site'], 
                    values: expanded ? 
                        [5847, 6234, 3766, 2345, 1567] : 
                        [5847, 6234, 3766] 
                }
            },
            locationChart: {
                location: { 
                    labels: expanded ? 
                        ['中国', '美国', '德国', '英国', '澳大利亚', '荷兰', '法国', '加拿大', '印度', '日本', '新加坡', '瑞典', '瑞士', '挪威', '丹麦'] : 
                        ['中国', '美国', '德国', '英国', '澳大利亚'], 
                    values: expanded ? 
                        [8945, 2341, 1876, 1654, 1031, 876, 734, 656, 578, 456, 345, 234, 198, 167, 145] : 
                        [8945, 2341, 1876, 1654, 1031] 
                },
                country: { 
                    labels: expanded ? 
                        ['中国', '美国', '德国', '英国', '澳大利亚', '荷兰', '法国', '加拿大', '印度', '日本'] : 
                        ['中国', '美国', '德国', '英国', '澳大利亚', '荷兰'], 
                    values: expanded ? 
                        [8945, 2341, 1876, 1654, 1031, 876, 734, 656, 578, 456] : 
                        [8945, 2341, 1876, 1654, 1031, 876] 
                },
                city: { 
                    labels: expanded ? 
                        ['北京', '上海', '深圳', '杭州', '广州', '成都', '南京', '武汉', '西安', '苏州', '天津', '重庆'] : 
                        ['北京', '上海', '深圳', '杭州', '广州'], 
                    values: expanded ? 
                        [2341, 2156, 1987, 1654, 1432, 1234, 1098, 987, 876, 765, 654, 543] : 
                        [2341, 2156, 1987, 1654, 1432] 
                }
            },
            salaryChart: {
                salary_range: { 
                    labels: expanded ? 
                        ['40K-60K', '60K-80K', '80K-100K', '100K-120K', '120K-140K', '140K-160K', '160K-180K', '180K-200K', '200K+'] : 
                        ['40K-60K', '60K-80K', '80K-100K', '100K-120K', '120K+'], 
                    values: expanded ? 
                        [1234, 3456, 4567, 3890, 2700, 2345, 1890, 1456, 1234] : 
                        [1234, 3456, 4567, 3890, 2700] 
                },
                avg_by_type: { 
                    labels: expanded ? 
                        ['Data Scientist', 'Data Engineer', 'Software Engineer', 'Data Analyst', 'ML Engineer', 'DevOps Engineer', 'Product Manager', 'Business Analyst'] : 
                        ['Data Scientist', 'Data Engineer', 'Software Engineer', 'Data Analyst'], 
                    values: expanded ? 
                        [115000, 108000, 102000, 78000, 112000, 105000, 125000, 85000] : 
                        [115000, 108000, 102000, 78000] 
                },
                avg_by_location: { 
                    labels: expanded ? 
                        ['San Francisco', 'New York', 'Seattle', 'Los Angeles', 'Chicago', 'Boston', 'Austin', 'Denver', 'Toronto', 'London'] : 
                        ['San Francisco', 'New York', 'Seattle', 'Los Angeles', 'Chicago'], 
                    values: expanded ? 
                        [145000, 125000, 115000, 108000, 95000, 118000, 102000, 98000, 85000, 78000] : 
                        [145000, 125000, 115000, 108000, 95000] 
                }
            },
            timeChart: {
                daily: { 
                    labels: expanded ? 
                        ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5', 'Day 6', 'Day 7', 'Day 8', 'Day 9', 'Day 10', 'Day 11', 'Day 12', 'Day 13', 'Day 14'] : 
                        ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5', 'Day 6', 'Day 7'], 
                    values: expanded ? 
                        [156, 189, 178, 203, 245, 167, 134, 198, 176, 221, 189, 203, 234, 187] : 
                        [156, 189, 178, 203, 245, 167, 134] 
                },
                weekly: { 
                    labels: expanded ? 
                        ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8'] : 
                        ['Week 1', 'Week 2', 'Week 3', 'Week 4'], 
                    values: expanded ? 
                        [1234, 1456, 1567, 1389, 1478, 1523, 1345, 1287] : 
                        [1234, 1456, 1567, 1389] 
                },
                monthly: { 
                    labels: expanded ? 
                        ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] : 
                        ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'], 
                    values: expanded ? 
                        [4567, 4890, 5234, 5678, 5432, 5789, 5234, 5456, 5123, 5345, 5567, 5789] : 
                        [4567, 4890, 5234, 5678, 5432, 5789] 
                }
            },
            skillsChart: {
                top_skills: { 
                    labels: expanded ? 
                        ['Python', 'SQL', 'R', 'Java', 'JavaScript', 'Tableau', 'Spark', 'AWS', 'Docker', 'Kubernetes', 'TensorFlow', 'PyTorch', 'React', 'Node.js', 'MongoDB', 'PostgreSQL', 'Git', 'Linux', 'Pandas', 'NumPy'] : 
                        ['Python', 'SQL', 'R', 'Java', 'JavaScript', 'Tableau', 'Spark', 'AWS'], 
                    values: expanded ? 
                        [8945, 7234, 5678, 4567, 4321, 3456, 2890, 2567, 2345, 2123, 1987, 1876, 1654, 1543, 1432, 1321, 1234, 1123, 1012, 987] : 
                        [8945, 7234, 5678, 4567, 4321, 3456, 2890, 2567] 
                },
                skills_by_type: { 
                    labels: expanded ? 
                        ['Python', 'SQL', 'Machine Learning', 'Statistics', 'Data Visualization', 'Big Data', 'Cloud Computing', 'API Development'] : 
                        ['Python', 'SQL', 'Machine Learning', 'Statistics'], 
                    values: expanded ? 
                        [3456, 2890, 2345, 1987, 1765, 1543, 1432, 1234] : 
                        [3456, 2890, 2345, 1987] 
                },
                emerging_skills: { 
                    labels: expanded ? 
                        ['GPT/LLM', 'Kubernetes', 'MLOps', 'Snowflake', 'DataBricks', 'Streamlit', 'FastAPI', 'GraphQL', 'Kafka', 'Redis'] : 
                        ['GPT/LLM', 'Kubernetes', 'MLOps', 'Snowflake'], 
                    values: expanded ? 
                        [1234, 987, 876, 654, 543, 432, 365, 298, 234, 187] : 
                        [1234, 987, 876, 654] 
                }
            },
            companyChart: {
                job_count: { 
                    labels: expanded ? 
                        ['Google', 'Microsoft', 'Amazon', 'Apple', 'Meta', 'Netflix', 'Tesla', 'Nvidia', 'OpenAI', 'Anthropic', 'Uber', 'Airbnb', 'Spotify', 'Adobe', 'Salesforce'] : 
                        ['Google', 'Microsoft', 'Amazon', 'Apple', 'Meta', 'Netflix'], 
                    values: expanded ? 
                        [456, 389, 367, 298, 245, 189, 167, 145, 134, 123, 112, 98, 87, 76, 65] : 
                        [456, 389, 367, 298, 245, 189] 
                },
                avg_salary: { 
                    labels: expanded ? 
                        ['Netflix', 'Google', 'Meta', 'Apple', 'Microsoft', 'Amazon', 'Tesla', 'Nvidia', 'OpenAI', 'Anthropic'] : 
                        ['Netflix', 'Google', 'Meta', 'Apple', 'Microsoft'], 
                    values: expanded ? 
                        [185000, 165000, 158000, 152000, 148000, 145000, 172000, 178000, 195000, 188000] : 
                        [185000, 165000, 158000, 152000, 148000] 
                },
                growth_rate: { 
                    labels: expanded ? 
                        ['Tesla', 'Nvidia', 'OpenAI', 'Anthropic', 'Uber', 'Airbnb', 'Spotify', 'Adobe'] : 
                        ['Tesla', 'Nvidia', 'OpenAI', 'Anthropic'], 
                    values: expanded ? 
                        [45, 38, 67, 89, 23, 18, 15, 12] : 
                        [45, 38, 67, 89] 
                }
            }
        };
        
        return mockData[chartId]?.[dimension] || { labels: [], values: [] };
    }
    
    getChartConfig(chartType, data, chartId) {
        const colors = [
            '#667eea', '#764ba2', '#f093fb', '#f5576c', '#4facfe', '#00f2fe',
            '#43e97b', '#38f9d7', '#ffecd2', '#fcb69f', '#a8edea', '#fed6e3',
            '#ff9a9e', '#fecfef', '#fecfef', '#a8edea'
        ];
        
        const baseConfig = {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: chartType === 'horizontalBar' ? 'top' : 'bottom',
                    labels: {
                        usePointStyle: true,
                        padding: 20
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    borderColor: '#667eea',
                    borderWidth: 1
                }
            },
            scales: {}
        };
        
        switch (chartType) {
            case 'doughnut':
                return {
                    type: 'doughnut',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            data: data.values,
                            backgroundColor: colors,
                            borderWidth: 2,
                            borderColor: '#fff',
                            hoverBorderWidth: 3
                        }]
                    },
                    options: {
                        ...baseConfig,
                        cutout: '60%'
                    }
                };
                
            case 'bar':
                baseConfig.scales = {
                    y: { beginAtZero: true },
                    x: {}
                };
                
                return {
                    type: 'bar',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            data: data.values,
                            backgroundColor: colors[0],
                            borderColor: colors[1],
                            borderWidth: 1,
                            borderRadius: 4
                        }]
                    },
                    options: {
                        ...baseConfig,
                        plugins: {
                            ...baseConfig.plugins,
                            legend: { display: false }
                        }
                    }
                };
                
            case 'horizontalBar':
                baseConfig.scales = {
                    x: { beginAtZero: true },
                    y: {}
                };
                
                return {
                    type: 'bar',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            data: data.values,
                            backgroundColor: colors.slice(0, data.labels.length),
                            borderWidth: 1,
                            borderRadius: 4
                        }]
                    },
                    options: {
                        ...baseConfig,
                        indexAxis: 'y',
                        plugins: {
                            ...baseConfig.plugins,
                            legend: { display: false }
                        }
                    }
                };
                
            case 'line':
                baseConfig.scales = {
                    y: { beginAtZero: true },
                    x: {}
                };
                
                return {
                    type: 'line',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: '数量',
                            data: data.values,
                            borderColor: colors[0],
                            backgroundColor: colors[0] + '20',
                            fill: true,
                            tension: 0.4,
                            pointBackgroundColor: colors[0],
                            pointBorderColor: '#fff',
                            pointBorderWidth: 2,
                            pointRadius: 5
                        }]
                    },
                    options: baseConfig
                };
                
            case 'area':
                baseConfig.scales = {
                    y: { beginAtZero: true },
                    x: {}
                };
                
                return {
                    type: 'line',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: '数量',
                            data: data.values,
                            borderColor: colors[0],
                            backgroundColor: colors[0] + '40',
                            fill: true,
                            tension: 0.4
                        }]
                    },
                    options: baseConfig
                };
                
            case 'radar':
                return {
                    type: 'radar',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: '数量',
                            data: data.values,
                            borderColor: colors[0],
                            backgroundColor: colors[0] + '20',
                            pointBackgroundColor: colors[0],
                            pointBorderColor: '#fff',
                            pointHoverBackgroundColor: '#fff',
                            pointHoverBorderColor: colors[0]
                        }]
                    },
                    options: {
                        ...baseConfig,
                        scales: {
                            r: { beginAtZero: true }
                        }
                    }
                };
                
            default:
                return baseConfig;
        }
    }
    
    async loadJobsTable() {
        try {
            const params = new URLSearchParams({
                page: this.currentPage,
                page_size: this.pageSize,
                ...this.currentFilters
            });
            
            const response = await fetch(`${this.apiBaseUrl}/jobs?${params}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
            this.displayJobsTable(result.jobs);
            this.updatePagination(result.pagination);
            this.totalJobs = result.pagination.total_items;
            
        } catch (error) {
            console.error('加载职位表格失败:', error);
            this.displayMockJobsTable();
        }
    }
    
    displayJobsTable(jobs) {
        // 新增：保存当前页职位数据，便于详情页上下切换
        this.currentJobs = Array.isArray(jobs) ? jobs : [];
        
        // 不再按匹配度排序，保持原始顺序
        const sortedJobs = [...jobs];
        
        // 显示卡片视图和表格视图
        this.displayJobsCards(sortedJobs);
        this.displayJobsTableView(sortedJobs);
    }
    
    // 新增：显示职位卡片视图
    displayJobsCards(jobs) {
        const cardsGrid = document.getElementById('jobCardsGrid');
        if (!cardsGrid) return;
        
        cardsGrid.innerHTML = '';
        
        jobs.forEach((job, index) => {
            const matchScore = job.match_score;
            const hasMatchScore = matchScore !== undefined && matchScore !== null;
            const matchClass = hasMatchScore ? this.getMatchScoreClass(matchScore) : '';
            const isRemote = job.job_work_from_home == 1;
            const matchPercentage = hasMatchScore ? Math.round(matchScore * 100) : 0;
            
            const cardDiv = document.createElement('div');
            cardDiv.className = 'job-card';
            cardDiv.style.animationDelay = `${index * 0.1}s`;
            
            cardDiv.innerHTML = `
                <div class="job-card-content">
                    <div class="job-card-header">
                        <div class="job-card-title">

                            <div>
                                <h4>${this.escapeHtml(job.job_title_short || job.job_title || 'N/A')}</h4>
                                <div class="job-badge">${this.escapeHtml(job.job_schedule_type || 'N/A')}</div>
                            </div>
                        </div>

                    </div>
                    
                    <div class="job-card-company">
                        <span>${this.escapeHtml(job.company_name || 'N/A')}</span>
                    </div>
                    
                    <div class="job-card-meta">
                        <span><i class="fas fa-map-marker-alt"></i> ${this.escapeHtml(job.job_location || 'N/A')}</span>
                        <span><i class="fas fa-dollar-sign"></i> ${job.salary_year_avg ? '$' + job.salary_year_avg.toLocaleString() : 'N/A'}</span>
                        <span><i class="fas fa-clock"></i> ${this.formatDate(job.job_posted_date)}</span>
                    </div>
                    

                    
                    <div class="job-card-tags">
                        ${this.formatSkills(job.job_skills)}
                    </div>
                    
                    <div class="job-card-actions">
                        <button class="btn btn-outline btn-sm">
                            <i class="fas fa-balance-scale"></i> 对比
                        </button>
                        <button class="btn btn-secondary btn-sm">
                            <i class="fas fa-heart"></i> 收藏
                        </button>
                        <button class="btn btn-primary btn-sm" onclick="jhDashboard.viewJobDetails('${job.id || ''}', 'jobs_list')">
                            <i class="fas fa-eye"></i> 查看详情
                        </button>
                    </div>
                </div>
            `;
            
            cardsGrid.appendChild(cardDiv);
        });
    }
    
    // 修改：显示表格视图（原来的displayJobsTable逻辑）
    displayJobsTableView(jobs) {
        const tbody = document.getElementById('jobsTableBody');
        if (!tbody) return;
        
        tbody.innerHTML = '';
        
        jobs.forEach((job, index) => {
            const row = document.createElement('tr');
            const fullTitle = job.job_title || '';
            const shortTitle = job.job_title_short || fullTitle || 'N/A';
            const isRemote = job.job_work_from_home == 1;
            const matchScore = job.match_score;
            const hasMatchScore = matchScore !== undefined && matchScore !== null;
            
            row.innerHTML = `
                <td>
                    <div class="job-title-container">
                        <div title="${this.escapeHtml(fullTitle)}">
                            <strong class="job-title-cell">${this.escapeHtml(shortTitle)}</strong>
                            <div class="job-title-sub" title="${this.escapeHtml(fullTitle)}">
                                ${this.escapeHtml(fullTitle)}
                            </div>
                        </div>
                    </div>
                </td>
                <td>${this.escapeHtml(job.company_name || 'N/A')}</td>
                <td>${this.escapeHtml(job.job_location || 'N/A')}</td>
                <td>${this.escapeHtml(job.job_schedule_type || 'N/A')}</td>
                <td>${job.salary_year_avg ? '$' + job.salary_year_avg.toLocaleString() : 'N/A'}</td>
                <td>${this.formatDate(job.job_posted_date)}</td>
                <td>${this.formatSkills(job.job_skills)}</td>
                <td class="remote-col">
                    <span class="remote-badge compact ${isRemote ? 'remote-yes' : 'remote-no'}" title="${isRemote ? '远程工作' : '现场办公'}">
                        <i class="fas ${isRemote ? 'fa-home' : 'fa-building'}"></i>
                        ${isRemote ? '远程' : '现场'}
                    </span>
                </td>
                <td>
                    <button class="btn btn-sm btn-primary action-btn" onclick="jhDashboard.viewJobDetails('${job.id || ''}', 'jobs_list')">
                        <i class="fas fa-eye"></i> 查看
                    </button>
                </td>
            `;
            

            
            tbody.appendChild(row);
        });
    }
    
    // 新增：视图切换方法
    switchView(viewType) {
        const cardViewBtn = document.getElementById('cardViewBtn');
        const tableViewBtn = document.getElementById('tableViewBtn');
        const cardsView = document.getElementById('cardsView');
        const tableView = document.getElementById('tableView');
        
        if (viewType === 'cards') {
            cardViewBtn?.classList.add('active');
            tableViewBtn?.classList.remove('active');
            cardsView.style.display = 'block';
            tableView.style.display = 'none';
        } else {
            cardViewBtn?.classList.remove('active');
            tableViewBtn?.classList.add('active');
            cardsView.style.display = 'none';
            tableView.style.display = 'block';
        }
    }
    
    // 新增：排序方法
    changeSorting(sortType) {
        if (!this.currentJobs.length) return;
        
        let sortedJobs = [...this.currentJobs];
        
        switch (sortType) {
            case 'match_score':
                sortedJobs.sort((a, b) => (b.match_score || 0) - (a.match_score || 0));
                break;
            case 'salary':
                sortedJobs.sort((a, b) => (b.salary_year_avg || 0) - (a.salary_year_avg || 0));
                break;
            case 'date':
                sortedJobs.sort((a, b) => new Date(b.job_posted_date || 0) - new Date(a.job_posted_date || 0));
                break;
            case 'company':
                sortedJobs.sort((a, b) => (a.company_name || '').localeCompare(b.company_name || ''));
                break;
        }
        
        this.displayJobsCards(sortedJobs);
        this.displayJobsTableView(sortedJobs);
    }
    
    // 更新活跃筛选显示
    updateActiveFilters() {
        const activeFiltersContainer = document.getElementById('activeFilters');
        const filterCount = document.getElementById('filterCount');
        
        // 清空容器
        if (activeFiltersContainer) activeFiltersContainer.innerHTML = '';
        
        const activeFilterEntries = Object.entries(this.currentFilters).filter(([key]) => key !== 'search');
        
        // 更新筛选计数
        if (filterCount) {
            if (activeFilterEntries.length > 0) {
                filterCount.textContent = activeFilterEntries.length;
                filterCount.style.display = 'block';
            } else {
                filterCount.style.display = 'none';
            }
        }
        
        // 显示完整的活跃筛选（如果存在activeFiltersContainer容器）
        activeFilterEntries.forEach(([key, value]) => {
            const displayName = this.getFilterDisplayName(key, value);
            
            // 完整筛选标签
            if (activeFiltersContainer) {
                const chip = document.createElement('div');
                chip.className = 'active-filter-chip';
                chip.innerHTML = `
                    <span>${displayName}</span>
                    <button class="remove-filter" onclick="dashboard.removeFilter('${key}')">
                        <i class="fas fa-times"></i>
                    </button>
                `;
                activeFiltersContainer.appendChild(chip);
            }
        });
    }
    
    // 切换筛选器面板
    toggleFilters() {
        const filtersPanel = document.getElementById('filtersPanel');
        const toggleBtn = document.getElementById('filterToggleBtn');
        
        if (!filtersPanel || !toggleBtn) return;
        
        const isVisible = filtersPanel.style.display !== 'none';
        
        if (isVisible) {
            filtersPanel.style.display = 'none';
            toggleBtn.classList.remove('active');
        } else {
            filtersPanel.style.display = 'block';
            toggleBtn.classList.add('active');
        }
    }
    
    // 更新筛选器计数
    updateFilterCount() {
        const filterCount = document.getElementById('filterCount');
        if (filterCount) {
            // 只计算有效的筛选器（排除空值、空字符串和未定义值）
            const activeFiltersCount = Object.entries(this.currentFilters || {})
                .filter(([key, value]) => value !== '' && value !== null && value !== undefined)
                .length;
            filterCount.textContent = activeFiltersCount;
            filterCount.style.display = activeFiltersCount > 0 ? 'inline-block' : 'none';
        }
    }
    
    // 新增：标签页切换功能
    switchFilterTab(tabName, element) {
        // 移除所有标签页的active类
        document.querySelectorAll('.filter-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        
        // 添加当前标签页的active类
        element.classList.add('active');
        
        // 隐藏所有内容区域
        document.querySelectorAll('.filter-tab-content').forEach(content => {
            content.classList.remove('active');
        });
        
        // 显示对应的内容区域
        const targetContent = document.getElementById(tabName + 'Tab');
        if (targetContent) {
            targetContent.classList.add('active');
        }
    }

    // 移除单个筛选器
    removeSingleFilter(filterKey) {
        if (!this.currentFilters) return;
        
        delete this.currentFilters[filterKey];
        
        // 重置对应的UI元素
        this.resetFilterUI(filterKey);
        
        // 重新加载数据和更新显示
        this.currentPage = 1;
        this.loadJobsTable();
        this.updateActiveFilters();
        this.updateFilterCount();
        
        // 中文通知消息
        const filterKeyLabels = {
            'job_type': '职位类型',
            'job_country': '工作地点',
            'job_schedule_type': '工作类型',
            'job_work_from_home': '远程工作',
            'salary_min': '最低薪资',
            'salary_max': '最高薪资',
            'search': '搜索关键词'
        };
        
        const keyLabel = filterKeyLabels[filterKey] || filterKey.replace('_', ' ');
        this.showNotification(`已移除筛选条件: ${keyLabel}`);
    }
    
    // 重置筛选器UI
    resetFilterUI(filterKey) {
        const filterMappings = {
            'job_type': 'jobType',
            'job_country': 'country', 
            'job_schedule_type': 'schedule',
            'job_work_from_home': 'remote'
        };
        
        // 重置标签式筛选器
        const reverseMapping = Object.entries(filterMappings).find(([key, value]) => key === filterKey);
        if (reverseMapping) {
            const uiKey = reverseMapping[1];
            const group = document.querySelector(`#${uiKey}Filters`);
            if (group) {
                // 移除所有active类
                group.querySelectorAll('.filter-tag').forEach(tag => {
                    tag.classList.remove('active');
                });
                // 激活"All"选项
                const allOption = group.querySelector('.filter-tag[data-value=""]');
                if (allOption) {
                    allOption.classList.add('active');
                }
            }
        }
        
        // 重置薪资输入框
        if (filterKey === 'salary_min') {
            const salaryMin = document.getElementById('salaryMin');
            if (salaryMin) salaryMin.value = '';
        }
        if (filterKey === 'salary_max') {
            const salaryMax = document.getElementById('salaryMax');
            if (salaryMax) salaryMax.value = '';
        }
        
        // 重置搜索框
        if (filterKey === 'search') {
            const searchInput = document.getElementById('searchInput');
            if (searchInput) searchInput.value = '';
        }
    }
    
    // 获取筛选器显示名称
    getFilterDisplayName(key, value) {
        const fieldNames = {
            job_schedule_type: 'Schedule',
            job_work_from_home: 'Remote',
            job_country: 'Country',
            salary_min: 'Min Salary',
            salary_max: 'Max Salary'
        };
        
        const fieldName = fieldNames[key] || key;
        
        if (key === 'job_work_from_home') {
            return `${fieldName}: ${value == 1 ? 'Remote' : 'On-site'}`;
        }
        
        return `${fieldName}: ${value}`;
    }
    
    // 移除单个筛选器
    removeFilter(filterKey) {
        delete this.currentFilters[filterKey];
        
        // 更新对应的标签状态
        const relatedTag = document.querySelector(`.filter-tag[data-filter="${filterKey}"].active`);
        if (relatedTag) {
            relatedTag.classList.remove('active');
        }
        
        // 清除薪资输入框
        if (filterKey === 'salary_min' || filterKey === 'salary_max') {
            const input = document.getElementById(filterKey === 'salary_min' ? 'salaryMin' : 'salaryMax');
            if (input) input.value = '';
        }
        
        // 更新显示和重新加载数据
        this.updateActiveFilters();
        this.currentPage = 1;
        this.loadJobsTable();
    }
    
    // 应用薪资筛选
    applySalaryFilter() {
        const minInput = document.getElementById('salaryMin');
        const maxInput = document.getElementById('salaryMax');
        
        const minValue = minInput?.value ? parseInt(minInput.value) : null;
        const maxValue = maxInput?.value ? parseInt(maxInput.value) : null;
        
        if (minValue !== null && minValue > 0) {
            this.currentFilters.salary_min = minValue;
        } else {
            delete this.currentFilters.salary_min;
        }
        
        if (maxValue !== null && maxValue > 0) {
            this.currentFilters.salary_max = maxValue;
        } else {
            delete this.currentFilters.salary_max;
        }
        
        this.updateActiveFilters();
        this.currentPage = 1;
        this.loadJobsTable();
        
        this.showNotification('Salary filter applied');
    }
    
    // 重置所有筛选器
    resetAllFilters() {
        // 清除所有筛选条件
        this.currentFilters = {};
        
        // 清除活跃标签
        const activeTags = document.querySelectorAll('.filter-tag.active');
        activeTags.forEach(tag => tag.classList.remove('active'));
        
        // 清除输入框
        const inputs = ['salaryMin', 'salaryMax', 'searchInput'];
        inputs.forEach(id => {
            const input = document.getElementById(id);
            if (input) input.value = '';
        });
        
        // 更新显示和重新加载数据
        this.updateActiveFilters();
        this.currentPage = 1;
        this.loadJobsTable();
        
        // 关闭筛选器面板
        const filtersPanel = document.getElementById('filtersPanel');
        const toggleBtn = document.querySelector('.filter-toggle-btn');
        if (filtersPanel) filtersPanel.style.display = 'none';
        if (toggleBtn) toggleBtn.classList.remove('active');
        
        this.showNotification('All filters reset');
    }
    
    displayMockJobsTable() {
        // 生成更大的模拟数据集
        const allMockJobs = this.generateLargeMockDataset();
        
        // 如果没有筛选条件，显示所有数据；否则应用筛选条件
        const hasFilters = Object.keys(this.currentFilters).length > 0;
        const filteredJobs = hasFilters ? this.applyFiltersToMockData(allMockJobs) : allMockJobs;
        
        // 按匹配度排序（如果有匹配度数据）
        const sortedJobs = [...filteredJobs];
        if (sortedJobs.some(job => job.match_score !== undefined)) {
            sortedJobs.sort((a, b) => (b.match_score || 0) - (a.match_score || 0));
        }
        
        // 计算分页
        const totalFiltered = sortedJobs.length;
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        const pageJobs = sortedJobs.slice(startIndex, endIndex);
        
        this.displayJobsTable(pageJobs);
        
        // 更新分页信息
        this.updatePagination({
            page: this.currentPage,
            page_size: this.pageSize,
            total_items: totalFiltered,
            total_pages: Math.ceil(totalFiltered / this.pageSize)
        });
        this.totalJobs = totalFiltered;
        
        // 更新统计信息
        this.updateJobStats(pageJobs);
    }
    
    generateLargeMockDataset() {
        const jobTitles = ['Senior Data Scientist', 'Data Engineer', 'Software Engineer', 'Data Analyst', 'Machine Learning Engineer'];
        const fullTitles = [
            'Senior Data Scientist - AI/ML Focus',
            'Data Engineer - Cloud Infrastructure',
            'Software Engineer - Full Stack',
            'Data Analyst - Business Intelligence',
            'Machine Learning Engineer - Deep Learning'
        ];
        const companies = ['Google', 'Microsoft', 'Amazon', 'Apple', 'Meta', 'Netflix', 'Tesla', 'Nvidia', 'OpenAI', 'Anthropic'];
        const locations = [
            'Mountain View, CA', 'Seattle, WA', 'New York, NY', 'Austin, TX', 'San Francisco, CA',
            'Los Angeles, CA', 'Chicago, IL', 'Boston, MA', 'Denver, CO', 'Portland, OR'
        ];
        const countries = ['United States', 'Germany', 'Canada', 'United Kingdom', 'Australia', 'Netherlands', 'France', 'Brazil'];
        const scheduleTypes = ['Full-time', 'Part-time', 'Contractor', 'Temp work', 'Internship'];
        const skillSets = [
            '["python", "sql", "machine learning", "tensorflow", "aws"]',
            '["java", "spring", "microservices", "docker", "kubernetes"]',
            '["javascript", "react", "node.js", "mongodb", "graphql"]',
            '["python", "pandas", "numpy", "tableau", "powerbi"]',
            '["scala", "spark", "hadoop", "kafka", "elasticsearch"]'
        ];
        
        // 生成2000条模拟数据（而不是500条）
        return Array.from({ length: 2000 }, (_, i) => {
            // 生成匹配度：前100个职位有较高匹配度，其余随机
            let matchScore;
            if (i < 20) {
                matchScore = 0.85 + Math.random() * 0.15; // 85-100%
            } else if (i < 100) {
                matchScore = 0.65 + Math.random() * 0.2; // 65-85%
            } else if (i < 500) {
                matchScore = 0.4 + Math.random() * 0.25; // 40-65%
            } else {
                matchScore = 0.2 + Math.random() * 0.2; // 20-40%
            }
            
            return {
                id: i + 1,
                job_title_short: jobTitles[i % jobTitles.length],
                job_title: fullTitles[i % fullTitles.length],
                company_name: companies[i % companies.length],
                job_location: locations[i % locations.length],
                job_country: countries[i % countries.length],
                job_schedule_type: scheduleTypes[i % scheduleTypes.length],
                salary_year_avg: 60000 + (i * 500) + Math.floor(Math.random() * 20000),
                job_posted_date: new Date(Date.now() - (i * 24 * 60 * 60 * 1000) - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000)).toISOString().split('T')[0],
                job_skills: skillSets[i % skillSets.length],
                job_work_from_home: Math.random() > 0.6 ? 1 : 0,
                match_score: matchScore
            };
        });
    }
    
    applyFiltersToMockData(jobs) {
        return jobs.filter(job => {
            // 搜索筛选
            if (this.currentFilters.search) {
                const searchTerm = this.currentFilters.search.toLowerCase();
                const searchableText = [
                    job.job_title_short,
                    job.job_title,
                    job.company_name,
                    job.job_location,
                    job.job_skills
                ].join(' ').toLowerCase();
                
                if (!searchableText.includes(searchTerm)) {
                    return false;
                }
            }
            
            // 职位类型筛选 (使用job_title_short字段)
            if (this.currentFilters.job_type) {
                const jobType = job.job_title_short || job.job_title;
                if (!jobType.includes(this.currentFilters.job_type)) {
                    return false;
                }
            }
            
            // 国家筛选 (使用job_country字段)
            if (this.currentFilters.job_country && job.job_country !== this.currentFilters.job_country) {
                return false;
            }
            
            // 工作类型筛选 (使用job_schedule_type字段)
            if (this.currentFilters.job_schedule_type && job.job_schedule_type !== this.currentFilters.job_schedule_type) {
                return false;
            }
            
            // 远程工作筛选 (使用job_work_from_home字段)
            if (this.currentFilters.job_work_from_home !== undefined && this.currentFilters.job_work_from_home !== '') {
                const isRemote = this.currentFilters.job_work_from_home === 'true';
                if ((isRemote && job.job_work_from_home !== 1) || (!isRemote && job.job_work_from_home !== 0)) {
                    return false;
                }
            }
            
            // 薪资范围筛选
            if (this.currentFilters.salary_min && job.salary_year_avg < parseInt(this.currentFilters.salary_min)) {
                return false;
            }
            
            if (this.currentFilters.salary_max && job.salary_year_avg > parseInt(this.currentFilters.salary_max)) {
                return false;
            }
            
            return true;
        });
    }
    
    updatePagination(pagination) {
        this.currentPage = pagination.page;
        this.totalPages = pagination.total_pages;
        
        // 更新分页信息显示
        const elements = {
            currentPage: document.getElementById('currentPage'),
            totalPages: document.getElementById('totalPages'),
            totalJobs: document.querySelector('.pagination-info .total-info #totalJobs')
        };
        
        if (elements.currentPage) elements.currentPage.textContent = this.currentPage;
        if (elements.totalPages) elements.totalPages.textContent = this.totalPages;
        if (elements.totalJobs) elements.totalJobs.textContent = this.formatNumber(pagination.total_items);
        
        // 更新分页按钮状态
        this.updatePaginationButtons();
        
        // 生成页码
        this.generatePageNumbers();
    }
    
    updatePaginationButtons() {
        const buttons = {
            firstBtn: document.getElementById('firstBtn'),
            prevBtn: document.getElementById('prevBtn'),
            nextBtn: document.getElementById('nextBtn'),
            lastBtn: document.getElementById('lastBtn')
        };
        
        if (buttons.firstBtn) buttons.firstBtn.disabled = this.currentPage <= 1;
        if (buttons.prevBtn) buttons.prevBtn.disabled = this.currentPage <= 1;
        if (buttons.nextBtn) buttons.nextBtn.disabled = this.currentPage >= this.totalPages;
        if (buttons.lastBtn) buttons.lastBtn.disabled = this.currentPage >= this.totalPages;
    }
    
    generatePageNumbers() {
        const pageNumbers = document.getElementById('pageNumbers');
        if (!pageNumbers) return;
        
        pageNumbers.innerHTML = '';
        
        const range = 5;
        let start = Math.max(1, this.currentPage - Math.floor(range / 2));
        let end = Math.min(this.totalPages, start + range - 1);
        
        if (end - start < range - 1) {
            start = Math.max(1, end - range + 1);
        }
        
        for (let i = start; i <= end; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `page-number ${i === this.currentPage ? 'active' : ''}`;
            pageBtn.textContent = i;
            pageBtn.onclick = () => this.goToPage(i);
            pageNumbers.appendChild(pageBtn);
        }
    }
    
    goToPage(page) {
        if (page >= 1 && page <= this.totalPages && page !== this.currentPage) {
            this.currentPage = page;
            this.loadJobsTable();
        }
    }
    
    firstPage() { this.goToPage(1); }
    previousPage() { this.goToPage(this.currentPage - 1); }
    nextPage() { this.goToPage(this.currentPage + 1); }
    lastPage() { this.goToPage(this.totalPages); }
    
    changePageSize(newSize) {
        this.pageSize = parseInt(newSize);
        this.currentPage = 1;
        this.loadJobsTable();
    }
    
    // 新的标签选择函数
    selectFilter(filterType, value, element) {
        // 确保参数有效
        if (!filterType || !element) {
            console.error('selectFilter: Invalid parameters', {filterType, value, element});
            return;
        }
        
        // 移除同组中其他标签的active类
        const group = element.parentElement;
        if (group) {
            group.querySelectorAll('.filter-tag').forEach(tag => {
                tag.classList.remove('active');
            });
        }
        
        // 添加当前标签的active类
        element.classList.add('active');
        
        // 更新筛选器状态
        const filterMappings = {
            'jobType': 'job_type',
            'country': 'job_country', 
            'schedule': 'job_schedule_type',
            'remote': 'job_work_from_home'
        };
        
        const filterKey = filterMappings[filterType];
        if (filterKey) {
            // 确保currentFilters对象存在
            if (!this.currentFilters) {
                this.currentFilters = {};
            }
            
            if (value && value !== '') {
                this.currentFilters[filterKey] = value;
            } else {
                delete this.currentFilters[filterKey];
            }
        }
        
        this.currentPage = 1;
        this.loadJobsTable();
        this.updateActiveFilters();
        this.updateFilterCount();
        
        // 中文通知消息
        const filterTypeLabels = {
            'jobType': '职位类型',
            'country': '工作地点',
            'schedule': '工作类型',
            'remote': '远程工作'
        };
        
        const typeLabel = filterTypeLabels[filterType] || filterType;
        const message = (value && value !== '') ? `已应用筛选: ${typeLabel} - ${value}` : `已移除 ${typeLabel} 筛选`;
        this.showNotification(message);
    }

    applyTableFilters() {
        // 添加薪资范围筛选
        const salaryMin = document.getElementById('salaryMin')?.value || '';
        const salaryMax = document.getElementById('salaryMax')?.value || '';
        
        if (salaryMin) {
            this.currentFilters.salary_min = salaryMin;
        } else {
            delete this.currentFilters.salary_min;
        }
        
        if (salaryMax) {
            this.currentFilters.salary_max = salaryMax;
        } else {
            delete this.currentFilters.salary_max;
        }
        
        this.currentPage = 1;
        this.loadJobsTable();
        this.updateActiveFilters();
        this.updateFilterCount();
        
        this.showNotification('Salary filters applied');
    }
    
    resetTableFilters() {
        // 重置所有标签式筛选器
        const filterGroups = [
            'jobTypeFilters', 'countryFilters', 'scheduleFilters', 'remoteFilters'
        ];
        
        filterGroups.forEach(groupId => {
            const group = document.getElementById(groupId);
            if (group) {
                // 移除所有active类
                group.querySelectorAll('.filter-tag').forEach(tag => {
                    tag.classList.remove('active');
                });
                // 激活第一个标签（通常是"All"选项）
                const firstTag = group.querySelector('.filter-tag');
                if (firstTag) {
                    firstTag.classList.add('active');
                }
            }
        });
        
        // 重置输入框
        const inputElements = ['salaryMin', 'salaryMax', 'searchInput'];
        inputElements.forEach(id => {
            const element = document.getElementById(id);
            if (element) {
                element.value = '';
            }
        });
        
        this.currentFilters = {};
        this.currentPage = 1;
        this.loadJobsTable();
        this.updateActiveFilters();
        this.updateFilterCount();
        
        this.showNotification('已清除所有筛选条件');
    }
    
    searchJobs() {
        const searchInput = document.getElementById('searchInput');
        if (searchInput) {
            const query = searchInput.value.trim();
            if (query) {
                this.currentFilters.search = query;
            } else {
                delete this.currentFilters.search;
            }
            this.currentPage = 1;
            this.loadJobsTable();
            this.updateActiveFilters();
            this.updateFilterCount();
        }
    }
    
    // 移除单个筛选条件
    removeFilter(filterKey) {
        delete this.currentFilters[filterKey];
        
        // 清空对应的输入控件
        const elementMappings = {
            job_type: 'jobTypeFilter',
            location: 'locationFilter',
            schedule_type: 'scheduleFilter',
            work_from_home: 'remoteFilter',
            salary_min: 'salaryMin',
            salary_max: 'salaryMax',
            search: 'searchInput'
        };
        
        const elementId = elementMappings[filterKey];
        if (elementId) {
            const element = document.getElementById(elementId);
            if (element) {
                element.value = '';
            }
        }
        
        this.currentPage = 1;
        this.loadJobsTable();
        this.updateActiveFilters();
        
        this.showNotification('筛选条件已移除');
    }
    
    sortTable(columnIndex) {
        this.showNotification('排序功能开发中...');
    }
    
    async viewJobDetails(jobId, source = 'jobs_list') {
        if (!jobId) {
            this.showNotification('岗位ID无效', 'error');
            return;
        }

        const modal = document.getElementById('jobDetailModal');
        const content = document.getElementById('jobDetailContent');
        
        // 显示模态框和加载状态
        modal.style.display = 'flex';
        setTimeout(() => modal.classList.add('show'), 10);
        
        // 显示加载状态
        content.innerHTML = `
            <div class="job-detail-loading">
                <i class="fas fa-spinner fa-spin"></i>
                <p>正在加载岗位详情...</p>
            </div>
        `;

        try {
            let job = null;
            
            // 如果是推荐职位，先尝试从本地数据获取
            if (source === 'recommended_positions') {
                // 从推荐职位数据中查找
                if (window.lastRecommendedPositions && Array.isArray(window.lastRecommendedPositions)) {
                    job = window.lastRecommendedPositions.find(p => String(p.id) === String(jobId));
                    console.log('本地查找职位ID:', jobId, '找到的职位:', job);
                }
                
                // 如果在本地找到了，直接显示，否则尝试API获取
                if (job) {
                    // 转换推荐职位数据格式为详情页面需要的格式
                    job = this.convertRecommendedJobToDetail(job);
                    this.currentJobIndex = window.lastRecommendedPositions.findIndex(j => String(j.id) === String(jobId));
                    this.currentJobs = window.lastRecommendedPositions; // 设置当前职位列表为推荐职位
                    this.currentJobDetail = job;
                    this.currentJobDetailSource = source;
                    this.displayJobDetail(job);
                    return;
                } else {
                    console.warn('在本地推荐职位数据中未找到ID为', jobId, '的职位，将尝试API获取');
                }
            }
            
            // 否则从API获取职位详情
            const response = await fetch(`${this.apiBaseUrl}/jobs/${jobId}`);
            const result = await response.json();

            if (!response.ok) {
                throw new Error(result.detail || '获取岗位详情失败');
            }

            job = result.data;
            // 记录当前职位索引与详情
            this.currentJobIndex = this.currentJobs.findIndex(j => String(j.id) === String(jobId));
            this.currentJobDetail = job;
            this.currentJobDetailSource = source;
            this.displayJobDetail(job);

        } catch (error) {
            console.error('获取岗位详情失败:', error);
            content.innerHTML = `
                <div class="job-detail-loading">
                    <i class="fas fa-exclamation-triangle" style="color: #ef4444;"></i>
                    <p style="color: #ef4444;">加载岗位详情失败: ${error.message}</p>
                    <button class="btn btn-secondary" onclick="jhDashboard.closeJobDetailModal()" style="margin-top: 16px;">
                        关闭
                    </button>
                </div>
            `;
        }
    }

    // 转换推荐职位数据格式为详情页面需要的格式
    convertRecommendedJobToDetail(recommendedJob) {
        // 如果有原始数据，优先使用原始数据
        if (recommendedJob.originalData) {
            return {
                ...recommendedJob.originalData,
                // 保留匹配相关的信息
                match_score: recommendedJob.match_score || recommendedJob.originalData.match_score || 0,
                match_reasons: recommendedJob.match_reasons || recommendedJob.reasons || recommendedJob.originalData.match_reasons || [],
                // 确保ID一致
                id: recommendedJob.id || recommendedJob.originalData.id
            };
        }
        
        // 回退到数据转换
        return {
            id: recommendedJob.id,
            job_title: recommendedJob.job_title || recommendedJob.title || '未知职位',
            job_title_short: recommendedJob.job_title_short || recommendedJob.title || recommendedJob.job_title || '未知职位',
            company_name: recommendedJob.company_name || recommendedJob.company || '未知公司',
            job_location: recommendedJob.job_location || recommendedJob.location || '未指定',
            job_schedule_type: recommendedJob.job_schedule_type || recommendedJob.work_type || '全职',
            job_posted_date: recommendedJob.job_posted_date || recommendedJob.posted_at || new Date().toISOString(),
            job_posted_date_formatted: recommendedJob.job_posted_date_formatted || recommendedJob.posted_at || '最近',
            job_country: recommendedJob.job_country || '中国',
            salary_year_avg: recommendedJob.salary_year_avg || recommendedJob.salary_range || recommendedJob.salary || '面议',
            job_is_remote: recommendedJob.job_is_remote || recommendedJob.remote || false,
            job_work_from_home: recommendedJob.job_work_from_home || recommendedJob.remote || false,
            job_skills: recommendedJob.job_skills || recommendedJob.skills || recommendedJob.required_skills || [],
            job_description: recommendedJob.job_description || recommendedJob.description || '暂无详细描述',
            job_benefits: recommendedJob.job_benefits || recommendedJob.benefits || [],
            job_requirements: recommendedJob.job_requirements || recommendedJob.requirements || [],
            company_logo: recommendedJob.company_logo || recommendedJob.logo || '',
            job_apply_link: recommendedJob.job_apply_link || recommendedJob.url || recommendedJob.apply_link || '',
            match_score: recommendedJob.match_score || 0,
            match_reasons: recommendedJob.match_reasons || recommendedJob.reasons || [],
            // 添加一些默认值
            job_via: recommendedJob.job_via || '智能推荐',
            job_apply_quality_score: recommendedJob.job_apply_quality_score || 85,
            job_no_degree_mention: recommendedJob.job_no_degree_mention || false,
            job_health_insurance: recommendedJob.job_health_insurance !== undefined ? recommendedJob.job_health_insurance : true,
            job_vacation: recommendedJob.job_vacation !== undefined ? recommendedJob.job_vacation : true,
            job_dental_coverage: recommendedJob.job_dental_coverage !== undefined ? recommendedJob.job_dental_coverage : true,
            job_vision_coverage: recommendedJob.job_vision_coverage !== undefined ? recommendedJob.job_vision_coverage : true,
            job_retirement_saving: recommendedJob.job_retirement_saving !== undefined ? recommendedJob.job_retirement_saving : true
        };
    }

    // 新增：上一条/下一条
    viewPrevJobDetail() {
        if (!Array.isArray(this.currentJobs) || this.currentJobs.length === 0) return;
        if (this.currentJobIndex <= 0) {
            this.showNotification('已经是当前页第一条', 'warning');
            return;
        }
        const prev = this.currentJobs[this.currentJobIndex - 1];
        if (prev && prev.id !== undefined) {
            this.viewJobDetails(prev.id, this.currentJobDetailSource);
        }
    }

    viewNextJobDetail() {
        if (!Array.isArray(this.currentJobs) || this.currentJobs.length === 0) return;
        if (this.currentJobIndex < 0) this.currentJobIndex = 0;
        if (this.currentJobIndex >= this.currentJobs.length - 1) {
            this.showNotification('已经是当前页最后一条', 'warning');
            return;
        }
        const next = this.currentJobs[this.currentJobIndex + 1];
        if (next && next.id !== undefined) {
            this.viewJobDetails(next.id, this.currentJobDetailSource);
        }
    }

    // 新增：复制到剪贴板
    async copyToClipboard(text) {
        try {
            if (navigator.clipboard && window.isSecureContext) {
                await navigator.clipboard.writeText(text);
            } else {
                const ta = document.createElement('textarea');
                ta.value = text;
                ta.style.position = 'fixed';
                ta.style.left = '-9999px';
                document.body.appendChild(ta);
                ta.focus();
                ta.select();
                document.execCommand('copy');
                ta.remove();
            }
            this.showNotification('已复制到剪贴板');
        } catch (e) {
            this.showNotification('复制失败', 'error');
        }
    }

    // 新增：生成职位摘要文本并复制
    copyJobSummary() {
        const job = this.currentJobDetail;
        if (!job) return;
        const skills = (() => {
            if (!job.job_skills) return [];
            if (Array.isArray(job.job_skills)) return job.job_skills;
            if (typeof job.job_skills === 'string') {
                try { return JSON.parse(job.job_skills); } catch { return job.job_skills.split(',').map(s => s.trim()).filter(Boolean); }
            }
            return [];
        })();
        const salary = job.salary_year_avg ? `$${Number(job.salary_year_avg).toLocaleString()}/年` : '面议';
        const summary = [
            `职位：${job.job_title_short || job.job_title || '未知'}`,
            `公司：${job.company_name || '未知'}`,
            `地点：${job.job_location || '未指定'} / ${job.job_country || ''}`,
            `类型：${job.job_schedule_type || '未指定'}；远程：${job.job_work_from_home == 1 ? '是' : '否'}`,
            `年薪：${salary}`,
            skills.length ? `技能：${skills.join(', ')}` : ''
        ].filter(Boolean).join('\n');
        this.copyToClipboard(summary);
    }

    // 新增：网页搜索（使用职位+公司）
    openJobSearch() {
        const job = this.currentJobDetail;
        if (!job) return;
        const q = encodeURIComponent(`${job.job_title_short || job.job_title || ''} ${job.company_name || ''}`.trim());
        const url = `https://www.google.com/search?q=${q}`;
        window.open(url, '_blank');
    }

    displayJobDetail(job) {
        const content = document.getElementById('jobDetailContent');
        const title = document.getElementById('jobDetailTitle');
        
        // 更新标题
        title.textContent = job.job_title_short || job.job_title || '岗位详情';

        // 处理技能数据
        let skills = [];
        if (job.job_skills) {
            if (Array.isArray(job.job_skills)) {
                skills = job.job_skills;
            } else if (typeof job.job_skills === 'string') {
                try {
                    skills = JSON.parse(job.job_skills);
                } catch {
                    skills = job.job_skills.split(',').map(s => s.trim()).filter(s => s);
                }
            }
        }

        // 格式化薪资
        const formatSalary = (salary) => {
            if (!salary) return '面议';
            if (typeof salary === 'number') {
                return `$${salary.toLocaleString()}/年`;
            }
            return salary;
        };

        // 格式化日期
        const formatDate = (dateStr) => {
            if (!dateStr) return '未知';
            try {
                return job.job_posted_date_formatted || this.formatDate(dateStr);
            } catch {
                return dateStr;
            }
        };

        // AI智能分析模块
        let aiSectionHtml = '';
        try {
            const analysis = window.lastAnalysisData || {};
            const userSkillScores = analysis && analysis.skill_matches ? analysis.skill_matches : {};
            const jobSkillsOriginal = Array.isArray(skills) ? skills : [];
            const jobSkillsLower = jobSkillsOriginal.map(s => String(s).trim()).filter(Boolean);
            
            const hasPersonalProfile = analysis && (analysis.skill_matches || analysis.resume_profile || analysis.experience_summary);
            
            if (!hasPersonalProfile) {
                // 无简历/技能画像：仅展示岗位信息与AI岗位解读
                const salaryAnalysis = this.analyzeSalaryCompetitiveness(job.salary_year_avg);
                const workModeAnalysis = this.analyzeWorkMode(job);
                const careerAnalysis = this.analyzeCareerPotential(job, skills);
                aiSectionHtml = `
                    <details class="job-section ai-analysis-section" open>
                        <summary class="job-section-title">
                            <i class="fas fa-info-circle"></i>
                            岗位解读（未上传简历，暂不进行个性化匹配）
                        </summary>
                        <div class="ai-module">
                            <div class="ai-module-header">
                                <i class="fas fa-building"></i>
                                <h4>岗位全貌</h4>
                            </div>
                            <div class="ai-module-content">
                                <ul class="bullet-list">
                                    <li><strong>核心技能：</strong>${this.escapeHtml(skills.slice(0,8).join(', ') || '未提供')}</li>
                                    <li><strong>工作地点/方式：</strong>${this.escapeHtml(job.job_location || '未指定')} · ${job.job_work_from_home == 1 ? '可远程' : '现场办公'}</li>
                                    <li><strong>日常职责摘要：</strong>${this.escapeHtml((job.job_highlights && job.job_highlights.Responsibilities && job.job_highlights.Responsibilities.slice(0,3).join('；')) || '暂无明确职责描述')}</li>
                                </ul>
                            </div>
                        </div>
                        <div class="ai-module">
                            <div class="ai-module-header">
                                <i class="fas fa-dollar-sign"></i>
                                <h4>薪资与发展</h4>
                                <span class="salary-level ${salaryAnalysis.level}">${salaryAnalysis.label}</span>
                            </div>
                            <div class="ai-module-content">
                                <div class="ai-insight"><p>${salaryAnalysis.insight}</p></div>
                                <div class="ai-suggestion"><strong>建议：</strong>${salaryAnalysis.suggestion}</div>
                            </div>
                        </div>
                        <div class="ai-module">
                            <div class="ai-module-header">
                                <i class="fas fa-rocket"></i>
                                <h4>岗位亮点</h4>
                            </div>
                            <div class="ai-module-content">
                                <div class="factors-grid">
                                    ${(job.job_highlights && job.job_highlights.Benefits ? job.job_highlights.Benefits.slice(0,6) : ['成长空间','团队氛围','技术栈更新']).map(t=>`<div class="factor-card positive"><i class="fas fa-check"></i>${this.escapeHtml(t)}</div>`).join('')}
                                </div>
                            </div>
                        </div>
                        <div class="ai-module">
                            <div class="ai-module-header">
                                <i class="fas fa-exclamation-circle"></i>
                                <h4>申请提示</h4>
                            </div>
                            <div class="ai-module-content">
                                <ul class="bullet-list">
                                    <li>建议先完成技能评估，解锁"技能匹配度、雷达图、匹配度分解"等个性化分析</li>
                                    <li>准备针对性的简历，突出${this.escapeHtml((skills[0]||'岗位核心技能'))}</li>
                                </ul>
                            </div>
                        </div>
                    </details>`;
            } else {
                // 有个人画像：展示个性化分析
            // 技能匹配分析
            const matched = jobSkillsLower
                .filter(s => userSkillScores.hasOwnProperty(String(s).toLowerCase()))
                .map(s => ({ name: s, score: Number(userSkillScores[String(s).toLowerCase()] || 0) }));
            const missing = jobSkillsLower.filter(s => !userSkillScores.hasOwnProperty(String(s).toLowerCase()));
            const matchScore = matched.length ? (matched.reduce((a,b)=> a + (isFinite(b.score)? b.score : 0), 0) / matched.length) : 0;
            const skillMatchPct = Math.max(0, Math.min(100, Math.round(matchScore * 10) / 10));
            
            // 薪资竞争力分析
            const salaryAnalysis = this.analyzeSalaryCompetitiveness(job.salary_year_avg);
            
            // 工作模式匹配度
            const workModeAnalysis = this.analyzeWorkMode(job);
            
            // 职业发展潜力
            const careerAnalysis = this.analyzeCareerPotential(job, skills);
            
            // 申请成功率预估
            const applicationAnalysis = this.analyzeApplicationSuccess(job, skillMatchPct);
            
            aiSectionHtml = `
                <details class="job-section ai-analysis-section" open>
                    <summary class="job-section-title">
                        <i class="fas fa-brain"></i>
                        AI 智能分析与建议
                    </summary>
                    
                    <!-- 技能匹配分析 -->
                    <div class="ai-module">
                        <div class="ai-module-header">
                            <i class="fas fa-code-branch"></i>
                            <h4>技能匹配度分析</h4>
                            <span class="match-score ${skillMatchPct >= 70 ? 'high' : skillMatchPct >= 40 ? 'medium' : 'low'}">${skillMatchPct}%</span>
                        </div>
                        <div class="ai-module-content">
                            <div class="ai-insight">
                                <p><strong>AI分析：</strong>${this.getSkillMatchInsight(skillMatchPct, matched.length, missing.length)}</p>
                            </div>
                            <div class="skill-breakdown">
                                ${matched.length > 0 ? `
                                    <div class="skill-category">
                                        <span class="category-label">✅ 匹配技能 (${matched.length}项)</span>
                                        <div class="skill-tags">
                                            ${matched.sort((a,b)=> (b.score||0) - (a.score||0)).slice(0, 8)
                                                .map(m => `<span class="skill-tag matched" title="${m.score}%">${this.escapeHtml(m.name)}</span>`).join('')}
                                        </div>
                                    </div>
                                ` : ''}
                                ${missing.length > 0 ? `
                                    <div class="skill-category">
                                        <span class="category-label">📚 需要学习 (${missing.length}项)</span>
                                        <div class="skill-tags">
                                            ${missing.slice(0, 6).map(s => `<span class="skill-tag missing">${this.escapeHtml(s)}</span>`).join('')}
                                        </div>
                                    </div>
                                ` : ''}
                            </div>
                            <div class="ai-suggestion">
                                <strong>建议：</strong>${this.getSkillSuggestion(skillMatchPct, missing)}
                            </div>
                        </div>
                    </div>
                    
                    <!-- 薪资竞争力分析 -->
                    <div class="ai-module">
                        <div class="ai-module-header">
                            <i class="fas fa-dollar-sign"></i>
                            <h4>薪资竞争力</h4>
                            <span class="salary-level ${salaryAnalysis.level}">${salaryAnalysis.label}</span>
                        </div>
                        <div class="ai-module-content">
                            <div class="ai-insight">
                                <p><strong>AI分析：</strong>${salaryAnalysis.insight}</p>
                            </div>
                            <div class="ai-suggestion">
                                <strong>建议：</strong>${salaryAnalysis.suggestion}
                            </div>
                        </div>
                    </div>
                    
                    <!-- 工作模式分析 -->
                    <div class="ai-module">
                        <div class="ai-module-header">
                            <i class="fas fa-laptop-house"></i>
                            <h4>工作模式匹配</h4>
                            <span class="work-mode-score ${workModeAnalysis.score >= 80 ? 'high' : workModeAnalysis.score >= 60 ? 'medium' : 'low'}">${workModeAnalysis.score}%</span>
                        </div>
                        <div class="ai-module-content">
                            <div class="ai-insight">
                                <p><strong>AI分析：</strong>${workModeAnalysis.insight}</p>
                            </div>
                            <div class="work-mode-details">
                                ${workModeAnalysis.features.map(f => `<div class="feature-item ${f.positive ? 'positive' : 'neutral'}"><i class="fas ${f.icon}"></i>${f.text}</div>`).join('')}
                            </div>
                            <div class="ai-suggestion">
                                <strong>建议：</strong>${workModeAnalysis.suggestion}
                            </div>
                        </div>
                    </div>
                    
                    <!-- 职业发展潜力 -->
                    <div class="ai-module">
                        <div class="ai-module-header">
                            <i class="fas fa-rocket"></i>
                            <h4>职业发展潜力</h4>
                            <span class="career-potential ${careerAnalysis.level}">${careerAnalysis.rating}</span>
                        </div>
                        <div class="ai-module-content">
                            <div class="ai-insight">
                                <p><strong>AI分析：</strong>${careerAnalysis.insight}</p>
                            </div>
                            <div class="career-factors">
                                ${careerAnalysis.factors.map(f => `<div class="factor-item"><i class="fas ${f.icon}"></i><span>${f.text}</span></div>`).join('')}
                            </div>
                            <div class="ai-suggestion">
                                <strong>建议：</strong>${careerAnalysis.suggestion}
                            </div>
                        </div>
                    </div>
                    
                    <!-- 申请成功率预估 -->
                    <div class="ai-module">
                        <div class="ai-module-header">
                            <i class="fas fa-target"></i>
                            <h4>申请成功率预估</h4>
                            <span class="success-rate ${applicationAnalysis.level}">${applicationAnalysis.rate}%</span>
                        </div>
                        <div class="ai-module-content">
                            <div class="ai-insight">
                                <p><strong>AI分析：</strong>${applicationAnalysis.insight}</p>
                            </div>
                            <div class="success-factors">
                                <div class="factors-grid">
                                    ${applicationAnalysis.factors.map(f => `
                                        <div class="factor-card ${f.positive ? 'positive' : 'negative'}">
                                            <i class="fas ${f.icon}"></i>
                                            <span>${f.text}</span>
                                            <div class="factor-impact">${f.impact}</div>
                                        </div>
                                    `).join('')}
                                </div>
                            </div>
                            <div class="ai-suggestion">
                                <strong>行动建议：</strong>${applicationAnalysis.action}
                            </div>
                        </div>
                    </div>
                    
                </details>`;
            }
        } catch (error) {
            console.warn('AI分析生成失败:', error);
            aiSectionHtml = `
                <details class="job-section" open>
                    <summary class="job-section-title">
                        <i class="fas fa-robot"></i>
                        智能分析
                    </summary>
                    <div class="ai-insight">
                        <p>正在为您准备详细的AI分析，请先完成技能评估以获得个性化建议。</p>
                    </div>
                </details>`;
        }

        // 新增：操作栏（复制、搜索、上一条、下一条）
        const actionBar = `
            <div class="job-detail-actions">
                <div class="left">
                    <button class="icon-btn" title="复制摘要 (C)" onclick="jhDashboard.copyJobSummary()"><i class="fas fa-copy"></i><span>复制摘要</span></button>
                    <button class="icon-btn" title="网页搜索 (G)" onclick="jhDashboard.openJobSearch()"><i class="fas fa-search"></i><span>网页搜索</span></button>
                </div>
                <div class="right">
                    <button class="icon-btn" title="上一条 (←)" onclick="jhDashboard.viewPrevJobDetail()"><i class="fas fa-arrow-left"></i><span>上一条</span></button>
                    <button class="icon-btn" title="下一条 (→)" onclick="jhDashboard.viewNextJobDetail()"><i class="fas fa-arrow-right"></i><span>下一条</span></button>
                </div>
            </div>`;

        // 渲染岗位详情
        content.innerHTML = `
            <div class="job-detail-content">
                <div class="job-detail-header">
                    <h2 class="job-title">${this.escapeHtml(job.job_title || job.job_title_short || '未知岗位')}</h2>
                    <div class="job-company">${this.escapeHtml(job.company_name || '未知公司')}</div>
                    ${actionBar}
                    <div class="job-meta-grid">
                        <div class="job-meta-item">
                            <i class="fas fa-map-marker-alt"></i>
                            <span>${this.escapeHtml(job.job_location || '未指定')}</span>
                        </div>
                        <div class="job-meta-item">
                            <i class="fas fa-briefcase"></i>
                            <span>${this.escapeHtml(job.job_schedule_type || '未指定')}</span>
                        </div>
                        <div class="job-meta-item">
                            <i class="fas fa-calendar-alt"></i>
                            <span>${formatDate(job.job_posted_date)}</span>
                        </div>
                        <div class="job-meta-item">
                            <i class="fas fa-globe"></i>
                            <span>${this.escapeHtml(job.job_country || '未指定')}</span>
                        </div>
                    </div>
                </div>

                <div class="job-detail-body">
                    <div class="job-info-grid">
                        <div class="job-info-item">
                            <div class="job-info-label">年薪</div>
                            <div class="job-info-value salary">${formatSalary(job.salary_year_avg)}</div>
                        </div>
                        <div class="job-info-item">
                            <div class="job-info-label">工作模式</div>
                            <div class="job-badges">
                                <span class="remote-badge ${job.job_work_from_home == 1 ? 'remote-yes' : 'remote-no'}" title="${job.job_work_from_home == 1 ? '远程工作' : '现场办公'}">
                                    <i class="fas ${job.job_work_from_home == 1 ? 'fa-home' : 'fa-building'}"></i>
                                    ${job.job_work_from_home == 1 ? '远程' : '现场'}
                                </span>
                                ${job.job_schedule_type ? `
                                <span class="schedule-badge"><i class="fas fa-briefcase"></i>${this.escapeHtml(job.job_schedule_type)}</span>
                                ` : ''}
                            </div>
                        </div>
                        <div class="job-info-item">
                            <div class="job-info-label">学历要求</div>
                            <div class="job-info-value">
                                ${job.job_no_degree_mention == 1 ? '无学历要求' : '有学历要求'}
                            </div>
                        </div>
                        <div class="job-info-item">
                            <div class="job-info-label">医疗保险</div>
                            <div class="job-info-value">
                                <i class="fas ${job.job_health_insurance == 1 ? 'fa-check-circle' : 'fa-times-circle'}"></i>
                                ${job.job_health_insurance == 1 ? '提供' : '不提供'}
                            </div>
                        </div>
                    </div>

                    ${aiSectionHtml}

                    ${job.job_via ? `
                        <details class="job-section" open>
                            <summary class="job-section-title">
                                <i class="fas fa-link"></i>
                                招聘来源
                            </summary>
                            <p class="job-description">${this.escapeHtml(job.job_via)}</p>
                        </details>
                    ` : ''}

                    ${skills.length > 0 ? `
                        <details class="job-section" open>
                            <summary class="job-section-title">
                                <i class="fas fa-tools"></i>
                                技能要求
                            </summary>
                            <div class="job-skills-grid">
                                ${skills.map(skill => 
                                    `<span class="job-skill-tag">${this.escapeHtml(skill)}</span>`
                                ).join('')}
                            </div>
                        </details>
                    ` : ''}

                    ${job.job_type_skills ? `
                        <details class="job-section">
                            <summary class="job-section-title">
                                <i class="fas fa-cogs"></i>
                                职位类型技能
                            </summary>
                            <p class="job-description">${this.escapeHtml(job.job_type_skills)}</p>
                        </details>
                    ` : ''}

                    ${job.search_location && job.search_location !== job.job_location ? `
                        <details class="job-section">
                            <summary class="job-section-title">
                                <i class="fas fa-search-location"></i>
                                搜索地区
                            </summary>
                            <p class="job-description">${this.escapeHtml(job.search_location)}</p>
                        </details>
                    ` : ''}

                    <details class="job-section" open>
                        <summary class="job-section-title">
                            <i class="fas fa-gift"></i>
                            福利待遇
                        </summary>
                        <div class="job-benefits">
                            ${job.job_work_from_home == 1 ? '<div class="job-benefit-tag"><i class="fas fa-home"></i>远程工作</div>' : ''}
                            ${job.job_health_insurance == 1 ? '<div class="job-benefit-tag"><i class="fas fa-heartbeat"></i>医疗保险</div>' : ''}
                            ${job.job_no_degree_mention == 1 ? '<div class="job-benefit-tag"><i class="fas fa-graduation-cap"></i>无学历要求</div>' : ''}
                            ${job.salary_year_avg ? `<div class=\"job-benefit-tag\"><i class=\"fas fa-dollar-sign\"></i>年薪 ${formatSalary(job.salary_year_avg)}</div>` : ''}
                        </div>
                    </details>
                </div>
            </div>
        `;
    }

    closeJobDetailModal() {
        const modal = document.getElementById('jobDetailModal');
        modal.classList.remove('show');
        setTimeout(() => {
            modal.style.display = 'none';
        }, 400);
    }

    // 初始化岗位详情模态框事件监听
    initJobDetailModal() {
        const modal = document.getElementById('jobDetailModal');
        
        // 点击背景关闭模态框
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                this.closeJobDetailModal();
            }
        });

        // ESC/左右方向键
        document.addEventListener('keydown', (e) => {
            const isOpen = modal.style.display === 'flex';
            if (!isOpen) return;
            if (e.key === 'Escape') {
                this.closeJobDetailModal();
            } else if (e.key === 'ArrowLeft') {
                this.viewPrevJobDetail();
            } else if (e.key === 'ArrowRight') {
                this.viewNextJobDetail();
            } else if (e.key.toLowerCase() === 'c') {
                this.copyJobSummary();
            } else if (e.key.toLowerCase() === 'g') {
                this.openJobSearch();
            }
        });
    }
    
    exportData() {
        this.showNotification('数据导出功能开发中...');
    }
    
    escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text ? text.replace(/[&<>"']/g, m => map[m]) : '';
    }

    // AI分析辅助方法
    getSkillMatchInsight(matchPct, matchedCount, missingCount) {
        if (matchPct >= 80) {
            return `您的技能组合与该职位高度匹配！已掌握${matchedCount}项核心技能，技能覆盖率达到${matchPct}%，属于理想候选人水平。`;
        } else if (matchPct >= 60) {
            return `您具备该职位的大部分技能要求，匹配度为${matchPct}%。已掌握${matchedCount}项技能，还有${missingCount}项技能需要加强。`;
        } else if (matchPct >= 40) {
            return `您具备该职位的部分基础技能，匹配度为${matchPct}%。需要重点提升${missingCount}项关键技能来增强竞争力。`;
        } else {
            return `该职位对您来说具有一定挑战性，当前匹配度为${matchPct}%。建议先学习${Math.min(missingCount, 3)}项核心技能再申请。`;
        }
    }

    getSkillSuggestion(matchPct, missingSkills) {
        if (matchPct >= 80) {
            return "您可以自信地申请此职位。建议在简历中突出展示匹配的技能项目经验。";
        } else if (matchPct >= 60) {
            const topMissing = missingSkills.slice(0, 2);
            return `重点学习${topMissing.join('、')}等技能，并通过项目实践来提升实战经验。`;
        } else if (matchPct >= 40) {
            const topMissing = missingSkills.slice(0, 3);
            return `建议先集中学习${topMissing.join('、')}等核心技能，可通过在线课程和实战项目快速提升。`;
        } else {
            return "建议先从基础技能开始学习，逐步构建完整的技能体系，再考虑申请类似职位。";
        }
    }

    analyzeSalaryCompetitiveness(salary) {
        if (!salary || salary === 0) {
            return {
                level: 'unknown',
                label: '待商议',
                insight: '该职位未明确薪资范围，可能采用面议模式，薪资弹性较大。',
                suggestion: '建议在面试时充分展示自己的价值，为薪资谈判做好准备。可参考同类职位的市场薪资水平。'
            };
        }

        // 基于常见薪资范围的简单分级
        if (salary >= 150000) {
            return {
                level: 'high',
                label: '高薪',
                insight: `年薪${(salary/10000).toFixed(1)}万属于行业高薪水平，体现了该职位的高价值和企业的重视程度。`,
                suggestion: '这是一个优质的高薪机会，建议充分准备面试，展示与薪资匹配的专业能力和项目经验。'
            };
        } else if (salary >= 100000) {
            return {
                level: 'good',
                label: '良好',
                insight: `年薪${(salary/10000).toFixed(1)}万处于市场中上游水平，薪资竞争力较强。`,
                suggestion: '薪资水平具有吸引力，建议评估职位发展前景和学习机会的综合价值。'
            };
        } else if (salary >= 60000) {
            return {
                level: 'medium',
                label: '中等',
                insight: `年薪${(salary/10000).toFixed(1)}万属于市场中等水平，适合作为职业发展的稳定选择。`,
                suggestion: '薪资中等但稳定，建议重点关注职位的学习成长机会和未来发展空间。'
            };
        } else {
            return {
                level: 'low',
                label: '偏低',
                insight: `年薪${(salary/10000).toFixed(1)}万低于市场平均水平，可能是初级职位或成长型公司。`,
                suggestion: '薪资偏低但可能有其他价值，如学习机会、股权激励等。建议全面评估职位的综合收益。'
            };
        }
    }

    analyzeWorkMode(job) {
        const features = [];
        let score = 50; // 基础分数

        // 远程工作
        if (job.job_work_from_home == 1) {
            features.push({
                icon: 'fa-home',
                text: '支持远程办公',
                positive: true
            });
            score += 20;
        } else {
            features.push({
                icon: 'fa-building',
                text: '需要现场办公',
                positive: false
            });
        }

        // 工作类型
        const scheduleType = job.job_schedule_type?.toLowerCase() || '';
        if (scheduleType.includes('full') || scheduleType.includes('全职')) {
            features.push({
                icon: 'fa-clock',
                text: '全职工作',
                positive: true
            });
            score += 15;
        } else if (scheduleType.includes('part') || scheduleType.includes('兼职')) {
            features.push({
                icon: 'fa-clock-o',
                text: '兼职工作',
                positive: false
            });
            score -= 10;
        }

        // 医疗保险
        if (job.job_health_insurance == 1) {
            features.push({
                icon: 'fa-heartbeat',
                text: '提供医疗保险',
                positive: true
            });
            score += 15;
        }

        const finalScore = Math.max(0, Math.min(100, score));

        let insight, suggestion;
        if (finalScore >= 80) {
            insight = '该职位的工作模式非常优秀，提供了灵活性和完善的保障，有利于工作生活平衡。';
            suggestion = '工作条件优越，建议优先考虑此职位，特别适合重视工作灵活性的求职者。';
        } else if (finalScore >= 60) {
            insight = '该职位的工作模式较为合理，提供了基本的工作保障和一定的灵活性。';
            suggestion = '工作条件良好，建议结合其他因素（如薪资、发展前景）综合考虑。';
        } else {
            insight = '该职位的工作模式相对传统，可能在灵活性方面有所限制。';
            suggestion = '建议重点关注职位的其他优势，如学习机会、团队文化等补偿因素。';
        }

        return {
            score: finalScore,
            features: features,
            insight: insight,
            suggestion: suggestion
        };
    }

    analyzeCareerPotential(job, skills) {
        let score = 0;
        const factors = [];

        // 技能复杂度分析
        const techSkills = skills.filter(s => 
            /react|vue|angular|python|java|javascript|typescript|node|aws|docker|kubernetes/i.test(s)
        );
        if (techSkills.length >= 3) {
            score += 30;
            factors.push({
                icon: 'fa-code',
                text: `涉及${techSkills.length}项热门技术栈`
            });
        }

        // 薪资水平影响发展潜力
        if (job.salary_year_avg >= 120000) {
            score += 25;
            factors.push({
                icon: 'fa-dollar-sign',
                text: '高薪职位，发展空间大'
            });
        } else if (job.salary_year_avg >= 80000) {
            score += 15;
            factors.push({
                icon: 'fa-chart-line',
                text: '薪资中上，有提升空间'
            });
        }

        // 工作模式加分
        if (job.job_work_from_home == 1) {
            score += 15;
            factors.push({
                icon: 'fa-laptop-house',
                text: '远程工作，发展灵活性高'
            });
        }

        // 公司规模推测
        if (job.job_health_insurance == 1) {
            score += 10;
            factors.push({
                icon: 'fa-building',
                text: '福利完善，公司相对稳定'
            });
        }

        // 学历要求
        if (job.job_no_degree_mention == 1) {
            score += 10;
            factors.push({
                icon: 'fa-graduation-cap',
                text: '注重能力，发展机会均等'
            });
        }

        const finalScore = Math.max(0, Math.min(100, score));
        
        let level, rating, insight, suggestion;
        if (finalScore >= 80) {
            level = 'high';
            rating = '优秀';
            insight = '该职位具有优秀的职业发展潜力，涉及前沿技术，薪资优渥，工作环境现代化。';
            suggestion = '强烈推荐申请，这类职位能够为您的职业生涯带来显著提升。';
        } else if (finalScore >= 60) {
            level = 'good';
            rating = '良好';
            insight = '该职位具有良好的发展前景，在技术栈和薪资水平方面都有一定优势。';
            suggestion = '值得考虑的职位，建议深入了解公司文化和团队情况。';
        } else if (finalScore >= 40) {
            level = 'medium';
            rating = '中等';
            insight = '该职位提供稳定的发展机会，适合作为职业发展的过渡选择。';
            suggestion = '可以作为备选方案，同时继续寻找更有挑战性的机会。';
        } else {
            level = 'low';
            rating = '有限';
            insight = '该职位的发展潜力相对有限，可能更适合初级阶段或稳定型求职者。';
            suggestion = '建议优先考虑其他更有发展前景的职位机会。';
        }

        return {
            level: level,
            rating: rating,
            factors: factors,
            insight: insight,
            suggestion: suggestion
        };
    }

    analyzeApplicationSuccess(job, skillMatchPct) {
        let baseRate = skillMatchPct * 0.6; // 技能匹配是主要因素
        const factors = [];

        // 技能匹配度
        if (skillMatchPct >= 80) {
            factors.push({
                icon: 'fa-check-circle',
                text: '技能高度匹配',
                impact: '+25%',
                positive: true
            });
            baseRate += 25;
        } else if (skillMatchPct >= 60) {
            factors.push({
                icon: 'fa-check',
                text: '技能基本匹配',
                impact: '+10%',
                positive: true
            });
            baseRate += 10;
        } else {
            factors.push({
                icon: 'fa-exclamation-triangle',
                text: '技能差距较大',
                impact: '-15%',
                positive: false
            });
            baseRate -= 15;
        }

        // 薪资期望合理性
        if (job.salary_year_avg && job.salary_year_avg < 150000) {
            factors.push({
                icon: 'fa-handshake',
                text: '薪资预期合理',
                impact: '+5%',
                positive: true
            });
            baseRate += 5;
        }

        // 学历要求
        if (job.job_no_degree_mention == 1) {
            factors.push({
                icon: 'fa-user-check',
                text: '门槛相对较低',
                impact: '+10%',
                positive: true
            });
            baseRate += 10;
        } else {
            factors.push({
                icon: 'fa-graduation-cap',
                text: '可能有学历要求',
                impact: '-5%',
                positive: false
            });
            baseRate -= 5;
        }

        // 工作模式优势
        if (job.job_work_from_home == 1) {
            factors.push({
                icon: 'fa-home',
                text: '远程工作加分',
                impact: '+5%',
                positive: true
            });
            baseRate += 5;
        }

        const finalRate = Math.max(5, Math.min(95, Math.round(baseRate)));
        
        let level, insight, action;
        if (finalRate >= 70) {
            level = 'high';
            insight = '您申请此职位的成功率很高，技能匹配度良好，建议尽快投递简历。';
            action = '立即准备简历和作品集，重点突出匹配技能的项目经验，并准备相关的技术面试。';
        } else if (finalRate >= 50) {
            level = 'medium';
            insight = '您有中等的申请成功机会，通过充分准备可以提高竞争力。';
            action = '完善技能短板，准备针对性的项目案例，充分展示学习能力和成长潜力。';
        } else {
            level = 'low';
            insight = '当前申请成功率较低，建议先提升相关技能再申请。';
            action = '制定技能提升计划，通过学习和实践项目来增强竞争力，也可考虑类似但要求稍低的职位。';
        }

        return {
            rate: finalRate,
            level: level,
            factors: factors,
            insight: insight,
            action: action
        };
    }
    
    // 删除翻译函数，直接显示原始英文数据
    
    formatDate(dateString) {
        if (!dateString) return 'N/A';
        try {
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN');
        } catch {
            return dateString;
        }
    }
    
    formatSkills(skillsString) {
        if (!skillsString) return 'N/A';
        try {
            const skills = JSON.parse(skillsString);
            if (Array.isArray(skills)) {
                return skills.slice(0, 3).map(skill => 
                    `<span class="skill-tag">${this.escapeHtml(skill)}</span>`
                ).join(' ');
            }
        } catch {
            // 如果不是JSON格式，直接显示
        }
        return this.escapeHtml(skillsString.substring(0, 50) + (skillsString.length > 50 ? '...' : ''));
    }
    
    // 初始化模态框
    initializeModal() {
        const modal = document.getElementById('chartModal');
        const closeBtn = document.getElementById('closeModal');
        const modalRefreshBtn = document.getElementById('modalRefreshBtn');
        const modalChartTypeSelect = document.getElementById('modalChartTypeSelect');
        const modalDimensionSelect = document.getElementById('modalDimensionSelect');
        
        // 关闭模态框事件
        closeBtn.addEventListener('click', () => this.closeChartModal());
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                this.closeChartModal();
            }
        });
        
        // 全局键盘快捷键
        document.addEventListener('keydown', (e) => {
            // ESC键关闭模态框
            if (e.key === 'Escape' && modal.classList.contains('show')) {
                this.closeChartModal();
            }
            // F5 快捷键刷新所有图表
            if (e.key === 'F5') {
                e.preventDefault();
                this.resizeAllCharts();
                this.showNotification('图表已刷新调整', 'success');
            }
            
            // 模态框专用快捷键
            if (modal.classList.contains('show')) {
                switch (e.key) {
                    case 'f':
                    case 'F':
                        if (e.ctrlKey || e.metaKey) {
                            e.preventDefault();
                            this.toggleModalFullscreen();
                        }
                        break;
                    case 'd':
                    case 'D':
                        if (e.ctrlKey || e.metaKey) {
                            e.preventDefault();
                            this.downloadModalChart();
                        }
                        break;
                    case 't':
                    case 'T':
                        if (e.ctrlKey || e.metaKey) {
                            e.preventDefault();
                            this.toggleChartDataView();
                        }
                        break;
                    case 'r':
                    case 'R':
                        if (e.ctrlKey || e.metaKey) {
                            e.preventDefault();
                            this.refreshModalChart();
                        }
                        break;
                    case 'z':
                    case 'Z':
                        if (e.ctrlKey || e.metaKey) {
                            e.preventDefault();
                            this.resetChartZoom();
                        }
                        break;
                }
            }
        });
        
        // 模态框内控件事件
        modalRefreshBtn.addEventListener('click', () => {
            if (this.currentModalChartId) {
                this.refreshModalChart();
            }
        });
        
        modalChartTypeSelect.addEventListener('change', () => {
            if (this.currentModalChartId) {
                this.refreshModalChart();
            }
        });
        
        modalDimensionSelect.addEventListener('change', () => {
            if (this.currentModalChartId) {
                this.refreshModalChart();
            }
        });
    }
    
    // 打开图表模态框
    async openChartModal(chartId) {
        const modal = document.getElementById('chartModal');
        if (!modal) return;
        
        this.currentModalChartId = chartId;
        
        // 更新模态框标题
        const modalTitle = document.getElementById('modalChartTitle');
        const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
        const chartTitle = chartCard ? chartCard.querySelector('.chart-title').textContent : '图表详情';
        modalTitle.innerHTML = `<i class="fas fa-chart-bar"></i> ${chartTitle}`;
        
        // 设置维度选择器选项
        this.updateModalDimensionOptions(chartId);
        
        // 设置当前图表ID到服务端
        await this.setCurrentChartOnServer(chartId);
        
        // 显示模态框
        modal.style.display = 'flex';
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);
        
        // 绑定事件监听器
        this.bindModalEventListeners();
        
        // 绑定帮助模态框事件
        this.bindHelpModalEvents();
        
        // 显示加载状态
        this.showModalLoading(true);
        
        // 加载图表数据
        await this.refreshModalChart();
        
        // 隐藏加载状态
        this.showModalLoading(false);
        
        // 确保图表在模态框显示后正确调整大小
        setTimeout(() => {
            if (this.modalChart) {
                this.modalChart.resize();
            }
        }, 400);
    }
    
    // 关闭图表模态框
    closeChartModal() {
        const modal = document.getElementById('chartModal');
        if (!modal) return;
        
        // 添加关闭动画类
        modal.classList.add('closing');
        modal.classList.remove('show');
        
        setTimeout(() => {
            modal.style.display = 'none';
            modal.classList.remove('closing', 'fullscreen');
            
            // 隐藏缩放提示
            const zoomHint = document.getElementById('zoomHint');
            if (zoomHint) {
                zoomHint.style.display = 'none';
            }
            
            // 销毁图表实例
            if (this.modalChart) {
                this.modalChart.destroy();
                this.modalChart = null;
            }

            // 隐藏AI聊天面板
            this.hideAIChat();

            this.currentModalChartId = null;
            this.unbindModalEventListeners();
        }, 300);
    }
    
    // 绑定模态框事件监听器
    bindModalEventListeners() {
        // 避免重复绑定
        this.unbindModalEventListeners();
        
        // 关闭按钮
        this.closeModalHandler = () => this.closeChartModal();
        document.getElementById('closeModal').addEventListener('click', this.closeModalHandler);
        
        // 全屏切换
        this.toggleFullscreenHandler = () => this.toggleModalFullscreen();
        document.getElementById('toggleFullscreen').addEventListener('click', this.toggleFullscreenHandler);
        
        // 下载图表
        this.downloadChartHandler = () => this.downloadModalChart();
        document.getElementById('downloadChart').addEventListener('click', this.downloadChartHandler);
        
        // 刷新图表
        this.modalRefreshHandler = () => this.refreshModalChart();
        document.getElementById('modalRefreshBtn').addEventListener('click', this.modalRefreshHandler);
        
        // 重置缩放
        this.resetZoomHandler = () => this.resetChartZoom();
        document.getElementById('resetZoomBtn').addEventListener('click', this.resetZoomHandler);
        
        // 数据表格切换
        this.toggleDataViewHandler = () => this.toggleChartDataView();
        document.getElementById('toggleDataView').addEventListener('click', this.toggleDataViewHandler);
        
        // 导出数据
        this.exportDataHandler = () => this.exportChartData();
        document.getElementById('exportDataBtn').addEventListener('click', this.exportDataHandler);
        
        // AI聊天切换
        this.toggleAIChatHandler = () => this.toggleAIChat();
        document.getElementById('toggleAIChat').addEventListener('click', this.toggleAIChatHandler);
        
        // 关闭AI聊天
        this.closeAIChatHandler = () => this.hideAIChat();
        document.getElementById('closeAIChat').addEventListener('click', this.closeAIChatHandler);
        
        // 显示帮助
        this.showHelpHandler = () => this.showHelpModal();
        document.getElementById('showHelp').addEventListener('click', this.showHelpHandler);
        
        // 图表类型选择
        this.chartTypeChangeHandler = () => this.refreshModalChart();
        document.getElementById('modalChartTypeSelect').addEventListener('change', this.chartTypeChangeHandler);
        
        // 维度选择
        this.dimensionChangeHandler = () => this.refreshModalChart();
        document.getElementById('modalDimensionSelect').addEventListener('change', this.dimensionChangeHandler);
        
        // 图表尺寸控制
        this.sizeControlHandler = (e) => {
            if (e.target.classList.contains('size-preset-btn')) {
                this.changeChartSize(e.target.dataset.size);
            }
        };
        document.querySelector('.chart-size-controls').addEventListener('click', this.sizeControlHandler);
        
        // ESC键关闭
        this.escKeyHandler = (e) => {
            if (e.key === 'Escape') {
                this.closeChartModal();
            }
        };
        document.addEventListener('keydown', this.escKeyHandler);
        
        // 点击背景关闭
        this.backdropClickHandler = (e) => {
            if (e.target.id === 'chartModal') {
                this.closeChartModal();
            }
        };
        document.getElementById('chartModal').addEventListener('click', this.backdropClickHandler);
    }
    
    // 解绑模态框事件监听器
    unbindModalEventListeners() {
        if (this.closeModalHandler) {
            document.getElementById('closeModal').removeEventListener('click', this.closeModalHandler);
        }
        if (this.toggleFullscreenHandler) {
            document.getElementById('toggleFullscreen').removeEventListener('click', this.toggleFullscreenHandler);
        }
        if (this.downloadChartHandler) {
            document.getElementById('downloadChart').removeEventListener('click', this.downloadChartHandler);
        }
        if (this.modalRefreshHandler) {
            document.getElementById('modalRefreshBtn').removeEventListener('click', this.modalRefreshHandler);
        }
        if (this.resetZoomHandler) {
            document.getElementById('resetZoomBtn').removeEventListener('click', this.resetZoomHandler);
        }
        if (this.toggleDataViewHandler) {
            document.getElementById('toggleDataView').removeEventListener('click', this.toggleDataViewHandler);
        }
        if (this.exportDataHandler) {
            document.getElementById('exportDataBtn').removeEventListener('click', this.exportDataHandler);
        }
        if (this.toggleAIChatHandler) {
            document.getElementById('toggleAIChat').removeEventListener('click', this.toggleAIChatHandler);
        }
        if (this.closeAIChatHandler) {
            document.getElementById('closeAIChat').removeEventListener('click', this.closeAIChatHandler);
        }
        if (this.showHelpHandler) {
            document.getElementById('showHelp').removeEventListener('click', this.showHelpHandler);
        }
        if (this.chartTypeChangeHandler) {
            document.getElementById('modalChartTypeSelect').removeEventListener('change', this.chartTypeChangeHandler);
        }
        if (this.dimensionChangeHandler) {
            document.getElementById('modalDimensionSelect').removeEventListener('change', this.dimensionChangeHandler);
        }
        if (this.sizeControlHandler) {
            const sizeControls = document.querySelector('.chart-size-controls');
            if (sizeControls) {
                sizeControls.removeEventListener('click', this.sizeControlHandler);
            }
        }
        if (this.escKeyHandler) {
            document.removeEventListener('keydown', this.escKeyHandler);
        }
        if (this.backdropClickHandler) {
            const modal = document.getElementById('chartModal');
            if (modal) {
                modal.removeEventListener('click', this.backdropClickHandler);
            }
        }
    }
    
    // 切换全屏模式
    toggleModalFullscreen() {
        const modal = document.getElementById('chartModal');
        const fullscreenBtn = document.getElementById('toggleFullscreen');
        const icon = fullscreenBtn.querySelector('i');
        
        modal.classList.toggle('fullscreen');
        
        if (modal.classList.contains('fullscreen')) {
            icon.className = 'fas fa-compress';
            fullscreenBtn.title = '退出全屏';
        } else {
            icon.className = 'fas fa-expand';
            fullscreenBtn.title = '全屏模式';
        }
        
        // 调整图表大小
        setTimeout(() => {
            if (this.modalChart) {
                this.modalChart.resize();
            }
        }, 100);
    }
    
    // 下载图表
    downloadModalChart() {
        if (!this.modalChart) return;
        
        try {
            const canvas = this.modalChart.canvas;
            const chartTitle = document.getElementById('modalChartTitle').textContent.replace(/^\s*\S+\s*/, ''); // 移除图标
            
            // 创建临时链接下载
            const link = document.createElement('a');
            link.download = `${chartTitle}_${new Date().toISOString().slice(0, 10)}.png`;
            link.href = canvas.toDataURL('image/png', 1.0);
            link.click();
            
            this.showNotification('图表已下载', 'success');
        } catch (error) {
            console.error('下载图表失败:', error);
            this.showNotification('下载失败，请重试', 'error');
        }
    }
    
    // 切换数据表格视图
    toggleChartDataView() {
        const chartCanvas = document.getElementById('modalChart');
        const dataTable = document.getElementById('chartDataTable');
        const toggleBtn = document.getElementById('toggleDataView');
        const icon = toggleBtn.querySelector('i');
        
        const isShowingTable = dataTable.classList.contains('show');
        
        if (isShowingTable) {
            // 显示图表
            dataTable.classList.remove('show');
            chartCanvas.style.display = 'block';
            icon.className = 'fas fa-table';
            toggleBtn.innerHTML = '<i class="fas fa-table"></i> 数据表格';
        } else {
            // 显示表格
            this.generateChartDataTable();
            dataTable.classList.add('show');
            chartCanvas.style.display = 'none';
            icon.className = 'fas fa-chart-bar';
            toggleBtn.innerHTML = '<i class="fas fa-chart-bar"></i> 图表视图';
        }
    }
    
    // 生成图表数据表格
    generateChartDataTable() {
        if (!this.modalChart || !this.modalChart.data) return;
        
        const data = this.modalChart.data;
        const table = document.getElementById('chartDataTableContent');
        const thead = table.querySelector('thead tr');
        const tbody = table.querySelector('tbody');
        
        // 清空现有内容
        thead.innerHTML = '';
        tbody.innerHTML = '';
        
        // 生成表头
        const headerRow = document.createElement('tr');
        headerRow.innerHTML = '<th>项目</th><th>数值</th><th>百分比</th>';
        thead.appendChild(headerRow);
        
        // 计算总值用于百分比计算
        const total = data.datasets[0]?.data?.reduce((sum, val) => sum + val, 0) || 0;
        
        // 生成表格内容
        data.labels?.forEach((label, index) => {
            const value = data.datasets[0]?.data[index] || 0;
            const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : '0.0';
            
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${label}</td>
                <td>${value.toLocaleString()}</td>
                <td>${percentage}%</td>
            `;
            tbody.appendChild(row);
        });
    }
    
    // 导出图表数据
    exportChartData() {
        if (!this.modalChart || !this.modalChart.data) return;
        
        try {
            const data = this.modalChart.data;
            const csvContent = this.convertChartDataToCSV(data);
            const chartTitle = document.getElementById('modalChartTitle').textContent.replace(/^\s*\S+\s*/, '');
            
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = `${chartTitle}_数据_${new Date().toISOString().slice(0, 10)}.csv`;
            link.click();
            
            this.showNotification('数据已导出', 'success');
        } catch (error) {
            console.error('导出数据失败:', error);
            this.showNotification('导出失败，请重试', 'error');
        }
    }
    
    // 将图表数据转换为CSV格式
    convertChartDataToCSV(data) {
        const headers = ['项目', '数值'];
        const rows = [headers.join(',')];
        
        data.labels?.forEach((label, index) => {
            const value = data.datasets[0]?.data[index] || 0;
            rows.push(`"${label}",${value}`);
        });
        
        return rows.join('\n');
    }
    
    // AI聊天相关方法
    toggleAIChat() {
        const rightPanel = document.getElementById('chartModalRightPanel');
        const toggleBtn = document.getElementById('toggleAIChat');
        
        if (rightPanel.classList.contains('show')) {
            this.hideAIChat();
        } else {
            this.showAIChat();
        }
    }
    
    showAIChat() {
        const rightPanel = document.getElementById('chartModalRightPanel');
        const toggleBtn = document.getElementById('toggleAIChat');
        
        rightPanel.classList.add('show');
        
        // 更新按钮状态
        if (toggleBtn) {
            toggleBtn.innerHTML = '<i class="fas fa-robot"></i> 隐藏AI';
            toggleBtn.classList.add('active');
        }
        
        // 初始化分割条拖拽功能
        initializeSplitter();
        
        // 聚焦到输入框
        setTimeout(() => {
            const input = document.getElementById('aiChatInput');
            if (input) input.focus();
        }, 300);
    }
    
    hideAIChat() {
        const rightPanel = document.getElementById('chartModalRightPanel');
        const toggleBtn = document.getElementById('toggleAIChat');
        const leftPanel = document.getElementById('chartModalLeftPanel');
        
        rightPanel.classList.remove('show');
        
        // 重置左栏宽度为100%
        if (leftPanel) {
            leftPanel.style.width = '100%';
        }
        
        // 更新按钮状态
        if (toggleBtn) {
            toggleBtn.innerHTML = '<i class="fas fa-robot"></i> AI分析';
            toggleBtn.classList.remove('active');
        }
    }
    
    // 绑定帮助模态框事件
    bindHelpModalEvents() {
        // 避免重复绑定
        this.unbindHelpModalEvents();
        
        // 关闭帮助按钮
        this.closeHelpHandler = () => this.closeHelpModal();
        document.getElementById('closeHelp').addEventListener('click', this.closeHelpHandler);
        
        // 点击背景关闭帮助
        this.helpBackdropClickHandler = (e) => {
            if (e.target.id === 'helpModal') {
                this.closeHelpModal();
            }
        };
        document.getElementById('helpModal').addEventListener('click', this.helpBackdropClickHandler);
    }
    
    // 解绑帮助模态框事件
    unbindHelpModalEvents() {
        if (this.closeHelpHandler) {
            const closeBtn = document.getElementById('closeHelp');
            if (closeBtn) {
                closeBtn.removeEventListener('click', this.closeHelpHandler);
            }
        }
        if (this.helpBackdropClickHandler) {
            const helpModal = document.getElementById('helpModal');
            if (helpModal) {
                helpModal.removeEventListener('click', this.helpBackdropClickHandler);
            }
        }
    }
    
    // 显示帮助模态框
    showHelpModal() {
        const helpModal = document.getElementById('helpModal');
        if (!helpModal) return;
        
        helpModal.style.display = 'flex';
        setTimeout(() => {
            helpModal.classList.add('show');
        }, 10);
    }
    
    // 关闭帮助模态框
    closeHelpModal() {
        const helpModal = document.getElementById('helpModal');
        if (!helpModal) return;
        
        helpModal.classList.remove('show');
        setTimeout(() => {
            helpModal.style.display = 'none';
        }, 300);
    }
    
    // 获取缩放配置
    getZoomConfig(chartType) {
        const baseConfig = {
            zoom: {
                wheel: {
                    enabled: true,
                    speed: 0.1
                },
                pinch: {
                    enabled: true
                },
                mode: 'xy',
                threshold: 2,
                sensitivity: 3,
                // 保持坐标轴标签和刻度的可见性
                onZoomRejected: function(chart, event) {
                    console.log('缩放被拒绝', event);
                },
                onZoomComplete: function(chart) {
                    // 缩放完成后保持坐标轴的显示
                    chart.update('none');
                }
            },
            pan: {
                enabled: true,
                mode: 'xy',
                threshold: 10,
                speed: 20,
                modifierKey: null,
                onPanComplete: function(chart) {
                    // 平移完成后保持坐标轴的显示
                    chart.update('none');
                }
            }
        };

        // 根据图表类型优化缩放行为
        switch (chartType) {
            case 'pie':
            case 'doughnut':
                // 饼图只允许缩放，不允许平移
                return {
                    zoom: {
                        ...baseConfig.zoom,
                        mode: 'xy'
                    },
                    pan: {
                        enabled: false
                    }
                };
            
            case 'line':
            case 'area':
                // 线图和面积图优化x轴缩放，保持坐标轴标签显示
                return {
                    ...baseConfig,
                    zoom: {
                        ...baseConfig.zoom,
                        mode: 'xy'
                    },
                    pan: {
                        ...baseConfig.pan,
                        mode: 'xy'
                    },
                    limits: {
                        x: {min: 'original', max: 'original'},
                        y: {min: 'original', max: 'original'}
                    }
                };
            
            case 'bar':
            case 'horizontalBar':
                // 柱状图允许双轴缩放
                return {
                    ...baseConfig,
                    limits: {
                        x: {min: 'original', max: 'original'},
                        y: {min: 0, max: 'original'}
                    }
                };
            
            case 'scatter':
            case 'bubble':
                // 散点图和气泡图允许完全自由缩放
                return baseConfig;
            
            default:
                return {
                    ...baseConfig,
                    limits: {
                        x: {min: 'original', max: 'original'},
                        y: {min: 0, max: 'original'}
                    }
                };
        }
    }
    
    // 重置图表缩放
    resetChartZoom() {
        if (!this.modalChart) {
            this.showNotification('没有可重置的图表', 'warning');
            return;
        }
        
        try {
            // 重置缩放
            this.modalChart.resetZoom();
            this.showNotification('已重置图表缩放', 'success');
        } catch (error) {
            console.error('重置缩放失败:', error);
            this.showNotification('重置缩放失败', 'error');
        }
    }
    
    // 增强的错误恢复机制
    async recoverFromChartError() {
        if (!this.currentModalChartId) return;
        
        try {
            this.showNotification('正在尝试恢复图表...', 'info');
            
            // 清理旧的图表实例
            if (this.modalChart) {
                try {
                    this.modalChart.destroy();
                } catch (e) {
                    console.warn('销毁图表时出现错误:', e);
                }
                this.modalChart = null;
            }
            
            // 清理canvas元素
            const canvas = document.getElementById('modalChart');
            if (canvas) {
                const parent = canvas.parentNode;
                const newCanvas = document.createElement('canvas');
                newCanvas.id = 'modalChart';
                newCanvas.style.width = '100%';
                newCanvas.style.height = '100%';
                parent.removeChild(canvas);
                parent.appendChild(newCanvas);
            }
            
            // 重新创建图表
            await this.refreshModalChart();
            
            this.showNotification('图表已恢复', 'success');
        } catch (error) {
            console.error('图表恢复失败:', error);
            this.showNotification('图表恢复失败，请刷新页面', 'error');
        }
    }
    
    // 更改图表尺寸
    changeChartSize(size) {
        const container = document.getElementById('chartModalContainer');
        const buttons = document.querySelectorAll('.size-preset-btn');
        
        // 更新按钮状态
        buttons.forEach(btn => btn.classList.remove('active'));
        document.querySelector(`[data-size="${size}"]`).classList.add('active');
        
        // 调整容器高度
        switch (size) {
            case 'small':
                container.style.minHeight = '400px';
                break;
            case 'medium':
                container.style.minHeight = '500px';
                break;
            case 'large':
                container.style.minHeight = '650px';
                break;
        }
        
        // 调整图表大小
        setTimeout(() => {
            if (this.modalChart) {
                this.modalChart.resize();
            }
        }, 100);
    }
    
    // 显示/隐藏模态框加载状态
    showModalLoading(show) {
        const loadingEl = document.getElementById('chartModalLoading');
        if (loadingEl) {
            loadingEl.style.display = show ? 'flex' : 'none';
        }
    }
    
    // 更新模态框维度选择器选项
    updateModalDimensionOptions(chartId) {
        const modalDimensionSelect = document.getElementById('modalDimensionSelect');
        const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
        const originalSelect = chartCard?.querySelector('.dimension-select');
        
        if (originalSelect && modalDimensionSelect) {
            modalDimensionSelect.innerHTML = originalSelect.innerHTML;
            modalDimensionSelect.value = originalSelect.value;
        }
    }
    
    // 刷新模态框中的图表
    async refreshModalChart() {
        if (!this.currentModalChartId) return;
        
        const modalChartTypeSelect = document.getElementById('modalChartTypeSelect');
        const modalDimensionSelect = document.getElementById('modalDimensionSelect');
        const chartType = modalChartTypeSelect.value;
        const dimension = modalDimensionSelect.value;
        
        this.showModalLoading(true);
        
        try {
            // 销毁旧图表
            if (this.modalChart) {
                this.modalChart.destroy();
            }
            
            // 获取图表数据
            const response = await fetch(`${this.apiBaseUrl}/chart-data/${this.currentModalChartId}?dimension=${dimension}&expanded=true`);
            const chartData = await response.json();
            
            // 创建新图表
            const canvas = document.getElementById('modalChart');
            const ctx = canvas.getContext('2d');
            
            const config = this.createChartConfig(chartType, chartData, {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    intersect: false,
                    mode: 'index'
                },
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 13
                            }
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        titleColor: 'white',
                        bodyColor: 'white',
                        borderColor: '#667eea',
                        borderWidth: 1,
                        cornerRadius: 8,
                        displayColors: true,
                        titleFont: {
                            size: 14,
                            weight: 'bold'
                        },
                        bodyFont: {
                            size: 13
                        }
                    },
                    // 添加拖拽缩放插件
                    zoom: this.getZoomConfig(chartType)
                },
                animation: {
                    duration: 1000,
                    easing: 'easeInOutQuart'
                }
            });
            
            this.modalChart = new Chart(ctx, config);
            
        } catch (error) {
            console.error('刷新模态框图表失败:', error);
            this.showNotification('加载图表失败，正在尝试恢复...', 'warning');
            
            // 尝试错误恢复
            try {
                await this.recoverFromChartError();
            } catch (recoveryError) {
                console.error('图表恢复也失败了:', recoveryError);
                this.showNotification('图表无法恢复，请刷新页面', 'error');
            }
        } finally {
            this.showModalLoading(false);
        }
    }
    
    // 新增：切换图表展开状态
    async toggleChartExpanded(chartId) {
        try {
            // 切换展开状态
            if (this.expandedCharts.has(chartId)) {
                this.expandedCharts.delete(chartId);
            } else {
                this.expandedCharts.add(chartId);
            }
            const expanded = this.expandedCharts.has(chartId);
            
            console.log(`${chartId} 展开状态: ${expanded}`);
            
            // 更新按钮状态和视觉效果
            this.updateExpandButton(chartId, expanded);
            
            // 重新获取数据（根据展开状态可能显示不同数量的数据）
            await this.refreshChart(chartId, expanded);
            
            // 添加平滑滚动到展开的图表
            if (expanded) {
                const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
                if (chartCard) {
                    setTimeout(() => {
                        chartCard.scrollIntoView({ 
                            behavior: 'smooth', 
                            block: 'center' 
                        });
                    }, 300); // 等待动画完成
                }
            }
            
        } catch (error) {
            console.error(`切换${chartId}展开状态失败:`, error);
        }
    }
    
    // 新增：更新图表函数，确保正确渲染
    updateChart(chartId, data, chartType, dimension) {
        const canvas = document.getElementById(chartId);
        if (!canvas) {
            console.warn(`画布元素不存在: ${chartId}`);
            return;
        }
        
        const ctx = canvas.getContext('2d');
        
        // 销毁现有图表
        if (this.charts[chartId]) {
            this.charts[chartId].destroy();
        }
        
        // 创建新图表配置
        const config = this.createChartConfig(chartType, data, dimension);
        
        // 创建新图表
        this.charts[chartId] = new Chart(ctx, config);
        
        // 更新数据量指示器
        const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
        if (chartCard) {
            const itemCount = data.labels ? data.labels.length : 0;
            chartCard.setAttribute('data-items', itemCount);
        }
        
        // 同步表头选择器状态
        this.syncChartControls(chartId, chartType, dimension);
    }
    
    // 同步图表控件状态
    syncChartControls(chartId, chartType, dimension) {
        const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
        if (!chartCard) return;
        
        // 同步图表类型选择器
        const typeSelect = chartCard.querySelector('.chart-type-select');
        if (typeSelect && typeSelect.value !== chartType) {
            typeSelect.value = chartType;
        }
        
        // 同步维度选择器
        const dimensionSelect = chartCard.querySelector('.dimension-select');
        if (dimensionSelect && dimensionSelect.value !== dimension) {
            dimensionSelect.value = dimension;
        }
        
        // 更新图表标题
        this.updateChartTitle(chartId, dimension);
    }
    
    // 同步所有图表控件状态
    syncAllChartControls() {
        const chartIds = ['jobTypeChart', 'locationChart', 'salaryChart', 'timeChart', 'skillsChart', 'companyChart'];
        
        chartIds.forEach(chartId => {
            const config = this.userPreferences.chartConfigs[chartId];
            if (config) {
                this.syncChartControls(chartId, config.type, config.dimension);
            }
        });
    }
    
    // 新增：创建图表配置
    createChartConfig(type, data, dimensionOrOptions) {
        // 判断第三个参数是字符串还是对象
        let dimension = null;
        let customOptions = {};
        
        if (typeof dimensionOrOptions === 'string') {
            dimension = dimensionOrOptions;
        } else if (typeof dimensionOrOptions === 'object' && dimensionOrOptions !== null) {
            customOptions = dimensionOrOptions;
        }
        
        const commonOptions = {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                intersect: false,
                mode: 'index'
            },
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        padding: 10,
                        usePointStyle: true,
                        font: {
                            size: 12
                        }
                    }
                },
                title: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: 'white',
                    bodyColor: 'white',
                    borderColor: 'rgba(255, 255, 255, 0.2)',
                    borderWidth: 1,
                    cornerRadius: 6,
                    displayColors: true
                },
                zoom: this.getZoomConfig(type)
            },
            layout: {
                padding: {
                    top: 10,
                    right: 10,
                    bottom: 10,
                    left: 10
                }
            },
            animation: {
                duration: 1000,
                easing: 'easeInOutQuart'
            },
            scales: {
                x: {
                    display: true,
                    grid: {
                        display: true
                    },
                    ticks: {
                        display: true,
                        maxRotation: 45,
                        minRotation: 0
                    }
                },
                y: {
                    display: true,
                    grid: {
                        display: true
                    },
                    ticks: {
                        display: true
                    }
                }
            }
        };
        
        // 合并自定义选项
        const mergedOptions = this.deepMerge(commonOptions, customOptions);
        
        const config = {
            type: type,
            data: {
                labels: data.labels || [],
                datasets: [{
                    data: data.values || [],
                    backgroundColor: this.getChartColors(data.labels?.length || 0),
                    borderColor: this.getChartColors(data.labels?.length || 0, 0.8),
                    borderWidth: 1,
                    hoverBackgroundColor: this.getChartColors(data.labels?.length || 0, 0.9),
                    hoverBorderColor: this.getChartColors(data.labels?.length || 0, 1),
                    hoverBorderWidth: 2
                }]
            },
            options: mergedOptions
        };
        
        // 根据图表类型调整配置
        if (type === 'horizontalBar') {
            config.type = 'bar';
            config.options.indexAxis = 'y';
            config.options.plugins.legend.position = 'top';
        } else if (type === 'doughnut' || type === 'pie') {
            config.options.plugins.legend.position = 'right';
            config.options.layout.padding = 20;
            // 饼图和环形图不需要坐标轴
            delete config.options.scales;
        } else if (type === 'line') {
            config.data.datasets[0].fill = false;
            config.data.datasets[0].tension = 0.4;
            config.data.datasets[0].pointBackgroundColor = this.getChartColors(1)[0];
            config.data.datasets[0].pointBorderColor = '#fff';
            config.data.datasets[0].pointBorderWidth = 2;
            config.data.datasets[0].pointRadius = 4;
            config.data.datasets[0].pointHoverRadius = 6;
        }
        
        return config;
    }
    
    // 深度合并对象
    deepMerge(target, source) {
        const result = { ...target };
        
        for (const key in source) {
            if (source.hasOwnProperty(key)) {
                if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key])) {
                    result[key] = this.deepMerge(result[key] || {}, source[key]);
                } else {
                    result[key] = source[key];
                }
            }
        }
        
        return result;
    }
    
    // 新增：初始化窗口大小变化监听器
    initializeResizeHandler() {
        let resizeTimeout;
        window.addEventListener('resize', () => {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(() => {
                this.resizeAllCharts();
            }, 300);
        });
    }
    
    // 新增：调整所有图表大小
    resizeAllCharts() {
        Object.keys(this.charts).forEach(chartId => {
            if (this.charts[chartId]) {
                try {
                    this.charts[chartId].resize();
                } catch (error) {
                    console.warn(`图表 ${chartId} 调整大小失败:`, error);
                }
            }
        });
        
        // 如果模态框中有图表，也要调整
        if (this.modalChart) {
            try {
                this.modalChart.resize();
            } catch (error) {
                console.warn('模态框图表调整大小失败:', error);
            }
        }
    }
    
    // 新增：获取图表颜色
    getChartColors(count, alpha = 0.7) {
        const colors = [
            `rgba(255, 99, 132, ${alpha})`,
            `rgba(54, 162, 235, ${alpha})`,
            `rgba(255, 205, 86, ${alpha})`,
            `rgba(75, 192, 192, ${alpha})`,
            `rgba(153, 102, 255, ${alpha})`,
            `rgba(255, 159, 64, ${alpha})`,
            `rgba(199, 199, 199, ${alpha})`,
            `rgba(83, 102, 255, ${alpha})`,
            `rgba(255, 99, 255, ${alpha})`,
            `rgba(99, 255, 132, ${alpha})`
        ];
        
        // 如果需要更多颜色，生成随机颜色
        while (colors.length < count) {
            const r = Math.floor(Math.random() * 255);
            const g = Math.floor(Math.random() * 255);
            const b = Math.floor(Math.random() * 255);
            colors.push(`rgba(${r}, ${g}, ${b}, ${alpha})`);
        }
        
        return colors.slice(0, count);
    }
}

// 全局函数
function toggleTheme() {
    const currentTheme = dashboard.userPreferences.theme;
    const newTheme = currentTheme === 'light' ? 'dark' : 'light';
    dashboard.applyTheme(newTheme);
}

function toggleConfigPanel() {
    const panel = document.getElementById('configPanel');
    if (panel) {
        panel.classList.toggle('active');
    }
}

function resetLayout() {
    dashboard.resetLayout();
}

function saveLayout() {
    dashboard.saveLayout();
    dashboard.showNotification('布局已保存');
}

function goBack() {
    if (window.history.length > 1) {
        window.history.back();
    } else {
        window.location.href = '../index.html';
    }
}

// 页面函数
function firstPage() { dashboard.firstPage(); }
function previousPage() { dashboard.previousPage(); }
function nextPage() { dashboard.nextPage(); }
function lastPage() { dashboard.lastPage(); }
function changePageSize(size) { dashboard.changePageSize(size); }
function applyTableFilters() { dashboard.applyTableFilters(); }
function resetTableFilters() { dashboard.resetTableFilters(); }
function searchJobs() { dashboard.searchJobs(); }
function sortTable(index) { dashboard.sortTable(index); }
function exportData() { dashboard.exportData(); }
function refreshChart(chartId) { jhDashboard.refreshChart(chartId); }
function changeChartType(chartId, type) { jhDashboard.changeChartType(chartId, type); }
function changeDimension(chartId, dimension) { jhDashboard.changeDimension(chartId, dimension); }
function applySalaryFilter() { dashboard.applySalaryFilter(); }
function resetAllFilters() { dashboard.resetAllFilters(); }
function toggleFilters() { dashboard.toggleFilters(); }
function selectFilter(filterType, value, element) { 
    if (jhDashboard) {
        jhDashboard.selectFilter(filterType, value, element); 
    }
}

// 初始化仪表板
let dashboard;
let jhDashboard; // 全局引用，供HTML中的onclick事件使用

document.addEventListener('DOMContentLoaded', () => {
	dashboard = new JHDashboard();
	jhDashboard = dashboard; // 赋值给全局变量
	window.jhDashboard = dashboard; // 确保在内联事件中可用
	window.dashboard = dashboard; // 兼容现有 window 级别调用
	
	// 默认激活第一个标签页
	setTimeout(() => {
		initializeTabContent('visualization');
	}, 100); // 稍微延迟以确保仪表板初始化完成
});

// 添加通知动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOut {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
    
    .skill-tag {
        display: inline-block;
        background: var(--bg-secondary);
        color: var(--text-primary);
        padding: 0.2rem 0.5rem;
        border-radius: 12px;
        font-size: 0.75rem;
        margin: 0.1rem;
        border: 1px solid var(--border-light);
    }
    
    .remote-badge {
        padding: 0.2rem 0.5rem;
        border-radius: 4px;
        font-size: 0.75rem;
        font-weight: 500;
    }
    
    .remote-yes {
        background: #10b981;
        color: white;
    }
    
    .remote-no {
        background: var(--border-light);
        color: var(--text-secondary);
    }
`;
document.head.appendChild(style);

// ===========================================
// 主标签页切换功能
// ===========================================

// 全局变量保存当前活跃的标签页
let currentActiveTab = 'visualization';

/**
 * 切换主标签页
 * @param {string} tabId 标签页ID
 * @param {HTMLElement} buttonElement 按钮元素
 */
function switchMainTab(tabId, buttonElement) {
    // 移除所有标签页的活跃状态
    document.querySelectorAll('.main-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    
    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.remove('active');
    });
    
    // 激活选中的标签页
    buttonElement.classList.add('active');
    const targetContent = document.getElementById(tabId + '-tab');
    if (targetContent) {
        targetContent.classList.add('active');
    }
    
    currentActiveTab = tabId;
    
    // 根据标签页执行特定的初始化逻辑
    initializeTabContent(tabId);
}

/**
 * 初始化标签页内容
 * @param {string} tabId 标签页ID
 */
function initializeTabContent(tabId) {
    switch (tabId) {
        case 'visualization':
            // 数据可视化标签页初始化时立即加载数据
            if (jhDashboard) {
                jhDashboard.loadJobsData();
            }
            break;
        case 'self-analysis':
            initializeSelfAnalysis();
            break;
        case 'smart-matching':
            initializeSmartMatching();
            break;
        case 'interview-strategy':
            initializeInterviewStrategy();
            break;
        case 'ai-assistant':
            initializeAIAssistant();
            break;
    }
}

// ===========================================
// 自身分析功能
// ===========================================

let userSkills = []; // 存储用户技能

function initializeSelfAnalysis() {
    console.log('初始化自身分析模块...');
    
    // 初始化文件上传功能
    const resumeFile = document.getElementById('resumeFile');
    if (resumeFile) {
        resumeFile.addEventListener('change', handleResumeUpload);
    }
    
    // 初始化拖拽上传
    const uploadArea = document.getElementById('resumeUpload');
    if (uploadArea) {
        uploadArea.addEventListener('dragover', handleDragOver);
        uploadArea.addEventListener('drop', handleFileDrop);
        uploadArea.addEventListener('dragleave', handleDragLeave);
        uploadArea.addEventListener('click', () => {
            const input = document.getElementById('resumeFile');
            if (input) input.click();
        });
    }
    
    // 初始化手动填写表单
    initializeManualForm();
}

// 分析方式切换
function switchAnalysisMethod(method, buttonElement) {
    // 移除所有活跃状态
    document.querySelectorAll('.method-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelectorAll('.analysis-method-content').forEach(content => {
        content.classList.remove('active');
        // 确保隐藏所有方式面板
        content.style.display = 'none';
    });
    
    // 激活选中的方式
    buttonElement.classList.add('active');
    const target = document.getElementById(method + '-method');
    if (target) {
        target.classList.add('active');
        // 显示当前方式面板
        target.style.display = 'block';
    }

    // 确保方式选择器可见（可能之前被结果视图隐藏）
    const selector = document.querySelector('.analysis-method-selector');
    if (selector) {
        selector.style.display = 'block';
    }
    
    // 隐藏分析结果
    document.getElementById('analysisResults').style.display = 'none';
}

// 初始化手动填写表单
function initializeManualForm() {
    const skillInput = document.getElementById('skillInput');
    const manualForm = document.getElementById('manualResumeForm');
    
    if (skillInput) {
        skillInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                addSkillTag();
            }
        });
    }
    
    if (manualForm) {
        manualForm.addEventListener('submit', handleManualFormSubmit);
    }
}

// 添加技能标签
function addSkillTag() {
    const skillInput = document.getElementById('skillInput');
    const skillsTags = document.getElementById('skillsTags');
    const skill = skillInput.value.trim();
    
    if (skill && !userSkills.includes(skill)) {
        userSkills.push(skill);
        
        const tag = document.createElement('span');
        tag.className = 'skill-tag';
        tag.innerHTML = `
            ${skill}
            <i class="fas fa-times" onclick="removeSkillTag('${skill}', this)"></i>
        `;
        
        skillsTags.appendChild(tag);
        skillInput.value = '';
    }
}

// 移除技能标签
function removeSkillTag(skill, element) {
    userSkills = userSkills.filter(s => s !== skill);
    element.parentElement.remove();
}

// 清空手动表单
function clearManualForm() {
    document.getElementById('manualResumeForm').reset();
    userSkills = [];
    document.getElementById('skillsTags').innerHTML = '';
}

// 处理手动表单提交
async function handleManualFormSubmit(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const resumeData = {
        name: formData.get('name'),
        email: formData.get('email'),
        phone: formData.get('phone'),
        education: formData.get('education'),
        experience: formData.get('experience'),
        skills: userSkills,
        summary: formData.get('summary'),
        target_position: formData.get('target_position'),
        expected_salary: formData.get('expected_salary')
    };
    
    try {
        await analyzeManualResume(resumeData);
    } catch (error) {
        console.error('分析失败:', error);
        alert('分析失败，请稍后重试');
    }
}

// 拖拽事件处理
function handleDragOver(e) {
    e.preventDefault();
    e.currentTarget.style.borderColor = '#667eea';
    e.currentTarget.style.background = 'rgba(102, 126, 234, 0.05)';
}

function handleDragLeave(e) {
    e.currentTarget.style.borderColor = '';
    e.currentTarget.style.background = '';
}

function handleFileDrop(e) {
    e.preventDefault();
    const files = e.dataTransfer.files;
    if (files.length > 0) {
        processResumeFile(files[0]);
    }
    
    // 重置样式
    e.currentTarget.style.borderColor = '';
    e.currentTarget.style.background = '';
}

function handleResumeUpload(e) {
    const file = e.target.files[0];
    if (file) {
        processResumeFile(file);
    }
}

// 处理文件上传和分析
async function processResumeFile(file) {
    console.log('处理简历文件:', file.name);
    
    // 检查文件大小（10MB限制）
    if (file.size > 10 * 1024 * 1024) {
        alert('文件大小不能超过10MB');
        return;
    }
    
    // 显示上传进度
    showUploadProgress();
    
    try {
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await fetch('/api/jh/resume/upload', {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        console.log('文件上传成功:', result);
        
        // 显示分析结果
        displayAnalysisResults(result.analysis);
        
    } catch (error) {
        console.error('文件上传失败:', error);
        resetUploadArea();
        alert('文件上传失败，请稍后重试');
    }
}

// 分析手动输入的简历
async function analyzeManualResume(resumeData) {
    try {
        const response = await fetch('/api/jh/resume/manual', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(resumeData)
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        console.log('手动分析成功:', result);
        
        // 显示分析结果
        displayAnalysisResults(result.analysis);
        
    } catch (error) {
        console.error('手动分析失败:', error);
        throw error;
    }
}

// 显示上传进度
function showUploadProgress() {
    const uploadArea = document.getElementById('resumeUpload');
    const progressDiv = document.getElementById('uploadProgress');
    
    uploadArea.style.display = 'none';
    progressDiv.style.display = 'block';
    
    // 模拟进度
    let progress = 0;
    const interval = setInterval(() => {
        progress += Math.random() * 30;
        if (progress > 100) progress = 100;
        
        document.getElementById('uploadProgressBar').style.width = progress + '%';
        document.getElementById('uploadProgressText').textContent = `上传中... ${Math.round(progress)}%`;
        
        if (progress >= 100) {
            clearInterval(interval);
            document.getElementById('uploadProgressText').textContent = '分析中...';
        }
    }, 200);
}

// 重置上传区域
function resetUploadArea() {
    const progressDiv = document.getElementById('uploadProgress');
    const uploadArea = document.getElementById('resumeUpload');
    if (progressDiv) progressDiv.style.display = 'none';
    if (uploadArea) {
        // 恢复为样式表定义的显示方式（flex），避免按钮错位
        uploadArea.style.display = '';
        // 清理拖拽时设置的临时样式
        uploadArea.style.borderColor = '';
        uploadArea.style.background = '';
    }
}

// 显示分析结果
function displayAnalysisResults(analysisData) {
    // 隐藏方法选择区域，显示结果区域
    document.querySelector('.analysis-method-selector').style.display = 'none';
    document.querySelectorAll('.analysis-method-content').forEach(content => {
        content.style.display = 'none';
    });
    document.getElementById('analysisResults').style.display = 'block';
    
    // 缓存最近一次分析数据供推荐/对比等功能使用
    window.lastAnalysisData = analysisData;

    // 显示技能分析结果
    displaySkillAnalysis(analysisData.skill_matches);

    // 新增：匹配度分解图与强弱项小雷达
    renderMatchBreakdownChart(analysisData);
    // 渲染能力雷达图（如果数据可用）
    renderCapabilityRadarChart(analysisData);
    
    // 更新竞争力指标
    updateCompetitivenessMetrics(analysisData);
    
    // 显示推荐职位
    displayRecommendedPositions(analysisData.recommended_positions);
    
    // 显示技能建议
    displaySkillSuggestions(analysisData.missing_skills, analysisData.strength_areas);
    
    // 显示职业发展建议
    displayCareerSuggestions(analysisData.career_suggestions);

    // 渲染目标岗位适配度（如果后端提供）
    try {
        const card = document.getElementById('targetRoleCard');
        if (card) {
            const roleName = document.getElementById('targetRoleName');
            const coverageBar = document.getElementById('targetRoleCoverageProgress');
            const coverageValue = document.getElementById('targetRoleCoverageValue');
            const missingSkillsDiv = document.getElementById('missingTargetSkills');
            const role = analysisData.target_role;
            const coverage = analysisData.target_role_skill_coverage;
            const missing = analysisData.missing_target_skills || [];
            if (role && typeof coverage === 'number') {
                card.style.display = 'block';
                roleName.textContent = role;
                const pct = Math.max(0, Math.min(100, coverage));
                coverageBar.style.width = pct + '%';
                coverageValue.textContent = pct.toFixed(1) + '%';
                if (missing.length) {
                    missingSkillsDiv.innerHTML = missing.map(s => `<span class="skill-tag">${s}</span>`).join('');
                } else {
                    missingSkillsDiv.innerHTML = '<span class="no-data">已覆盖大部分关键技能</span>';
                }
            } else {
                card.style.display = 'none';
            }
        }
    } catch (e) {
        console.warn('渲染目标岗位适配度失败:', e);
    }
}

let capabilityRadarChartInstance = null;
// 兼容：导出到 window 以便清理
window.skillRadarChartInstance = window.skillRadarChartInstance || null;

function renderCapabilityRadarChart(analysisData) {
	const canvas = document.getElementById('capabilityRadarChart');
	if (!canvas) return;

	// 清理之前的图表实例
	if (capabilityRadarChartInstance) {
		capabilityRadarChartInstance.destroy();
		capabilityRadarChartInstance = null;
	}

	const dimensions = [];
	const values = [];

	// 优先使用后端提供的能力维度数据
	if (analysisData.capability_dimensions && Array.isArray(analysisData.capability_dimensions)) {
		analysisData.capability_dimensions.forEach(dim => {
			if (dim && typeof dim.name === 'string' && typeof dim.score === 'number') {
				dimensions.push(dim.name);
				values.push(Math.max(0, Math.min(100, dim.score)));
			}
		});
	}

	// 如果没有专门的能力维度数据，则智能生成
	if (dimensions.length === 0) {
		const norm = (v) => {
			if (v == null || isNaN(v)) return 0;
			if (v > 0 && v <= 1) return Math.round(v * 1000) / 10;
			return Math.max(0, Math.min(100, Math.round(v * 10) / 10));
		};

		// 分析技能数据以生成能力维度
		const skillValues = Object.values(analysisData.skill_matches || {});
		const skillKeys = Object.keys(analysisData.skill_matches || {});
		
		// 技术深度：基于最高技能分数
		const avgSkill = skillValues.length ? (skillValues.reduce((a,b)=>a+b,0) / skillValues.length) : 0;
		const sorted = [...skillValues].sort((a,b)=>b-a);
		const top3Avg = sorted.length ? (sorted.slice(0,3).reduce((a,b)=>a+b,0) / Math.min(3, sorted.length)) : 0;
		
		// 技术广度：基于技能覆盖面
		const skillsCount = skillKeys.length;
		const breadth = Math.min(100, skillsCount * 8 + (skillsCount > 10 ? 20 : 0));
		
		// 技能均衡度：基于技能分数的一致性
		const consistency = skillValues.length > 1 ? 
			Math.max(0, 100 - (Math.max(...skillValues) - Math.min(...skillValues)) * 2) : 
			avgSkill;
		
		// 项目经验评分
		const experienceScore = norm(
			analysisData.project_experience_score != null ? analysisData.project_experience_score :
			(analysisData.experience_years != null ? Math.min(100, analysisData.experience_years * 12) : 
			(analysisData.competitiveness_score || avgSkill))
		);
		
		// 学习能力：基于技能多样性和发展潜力
		const learningAbility = Math.min(100, 
			(breadth * 0.4) + (consistency * 0.3) + (experienceScore * 0.3)
		);
		
		// 市场竞争力
		const marketValue = norm(analysisData.competitiveness_score || avgSkill);
		
		// 沟通协作能力：基于综合表现推估
		const communicationScore = Math.min(100, 
			(avgSkill * 0.5) + (consistency * 0.3) + (breadth * 0.2)
		);
		
		// 问题解决能力：基于技术深度和经验
		const problemSolving = Math.min(100, 
			(top3Avg * 0.6) + (experienceScore * 0.4)
		);

		// 创新能力：基于技术广度和学习能力
		const innovation = Math.min(100, 
			(breadth * 0.5) + (learningAbility * 0.5)
		);

		const calculatedCapabilities = [
			{ name: '技术深度', value: norm(top3Avg) },
			{ name: '技术广度', value: norm(breadth) },
			{ name: '学习能力', value: norm(learningAbility) },
			{ name: '项目经验', value: experienceScore },
			{ name: '问题解决', value: norm(problemSolving) },
			{ name: '沟通协作', value: norm(communicationScore) },
			{ name: '创新思维', value: norm(innovation) },
			{ name: '市场价值', value: marketValue }
		];

		// 添加到维度数组
		calculatedCapabilities.forEach(cap => { 
			dimensions.push(cap.name); 
			values.push(cap.value); 
		});
		
		// 将计算结果保存到分析数据中，供详细分析使用
		analysisData.calculated_capabilities = calculatedCapabilities;
	}

	// 创建雷达图
	const ctx = canvas.getContext('2d');
	capabilityRadarChartInstance = new Chart(ctx, {
		type: 'radar',
		data: {
			labels: dimensions,
			datasets: [{
				label: '能力评估',
				data: values,
				backgroundColor: 'rgba(99, 102, 241, 0.15)',
				borderColor: 'rgba(99, 102, 241, 0.8)',
				pointBackgroundColor: 'rgba(99, 102, 241, 1)',
				pointBorderColor: '#ffffff',
				pointHoverBackgroundColor: '#ffffff',
				pointHoverBorderColor: 'rgba(99, 102, 241, 1)',
				pointRadius: 6,
				pointHoverRadius: 8,
				borderWidth: 3,
				tension: 0.1
			}]
		},
		options: {
			responsive: true,
			maintainAspectRatio: false,
			plugins: {
				legend: { 
					display: false
				},
				tooltip: { 
					enabled: true,
					backgroundColor: 'rgba(17, 24, 39, 0.9)',
					titleColor: '#ffffff',
					bodyColor: '#ffffff',
					borderColor: 'rgba(99, 102, 241, 0.5)',
					borderWidth: 1,
					cornerRadius: 8,
					displayColors: false,
					callbacks: {
						title: function(tooltipItems) {
							return tooltipItems[0].label;
						},
						label: function(context) {
							const score = context.parsed.r;
							let level = '';
							if (score >= 85) level = ' (卓越)';
							else if (score >= 70) level = ' (优秀)';
							else if (score >= 55) level = ' (良好)';
							else if (score >= 40) level = ' (一般)';
							else level = ' (待提升)';
							return `评分: ${score.toFixed(1)}${level}`;
						}
					}
				}
			},
			scales: {
				r: {
					suggestedMin: 0,
					suggestedMax: 100,
					ticks: { 
						stepSize: 20,
					color: 'var(--text-secondary)',
						font: { size: 11 },
						backdropColor: 'transparent'
					},
					grid: { 
						color: 'rgba(148, 163, 184, 0.3)',
						lineWidth: 1
					},
					angleLines: { 
						color: 'rgba(148, 163, 184, 0.2)',
						lineWidth: 1
					},
					pointLabels: { 
						color: 'var(--text-primary)',
						font: { 
							size: 12,
							weight: '500'
						},
						padding: 15
					}
				}
			},
			interaction: {
				intersect: false,
				mode: 'index'
			},
			animation: {
				duration: 2000,
				easing: 'easeOutCubic'
			}
		}
	});
}

function renderSkillRadarChart(analysisData) {
	const canvas = document.getElementById('skillRadarChart');
	if (!canvas || typeof Chart === 'undefined') return;

	const skillsObj = (analysisData && (analysisData.skill_matches || analysisData.skills)) || {};
	const entries = Object.entries(skillsObj)
		.map(([k, v]) => {
			const parsed = typeof v === 'string' ? parseFloat(v.replace('%', '')) : v;
			const num = Number.isFinite(parsed) ? parsed : 0;
			return [k, num];
		})
		.filter(([_, v]) => v > 0)
		.sort((a, b) => b[1] - a[1])
		.slice(0, 6);
	if (entries.length === 0) return;

	const labels = entries.map(([k]) => k);
	const values = entries.map(([_, v]) => Math.max(0, Math.min(100, v)));

	if (window.skillRadarChartInstance) {
		try { window.skillRadarChartInstance.destroy(); } catch (e) {}
		window.skillRadarChartInstance = null;
	}

	const ctx = canvas.getContext('2d');
	window.skillRadarChartInstance = new Chart(ctx, {
		type: 'radar',
		data: {
			labels,
			datasets: [{
				label: '技能匹配度',
				data: values,
				backgroundColor: 'rgba(59, 130, 246, 0.2)',
				borderColor: 'rgba(59, 130, 246, 1)',
				pointBackgroundColor: 'rgba(59, 130, 246, 1)',
				pointBorderColor: '#fff'
			}]
		},
		options: {
			responsive: true,
			maintainAspectRatio: false,
			scales: {
				r: {
					suggestedMin: 0,
					suggestedMax: 100,
					ticks: { stepSize: 20 },
					grid: { color: 'rgba(0,0,0,0.1)' },
					angleLines: { color: 'rgba(0,0,0,0.1)' },
					pointLabels: { color: 'var(--text-primary)' }
				}
			},
			plugins: {
				legend: { display: false },
				tooltip: { enabled: true }
			}
		}
	});
}

// 显示技能分析结果
function displaySkillAnalysis(skillMatches) {
    const container = document.getElementById('skillAnalysisResults');
    if (!container) return;
    
    if (!skillMatches || Object.keys(skillMatches).length === 0) {
        container.innerHTML = '<p class="no-data">未检测到相关技能信息</p>';
        return;
    }
    
    const sortedSkills = Object.entries(skillMatches).sort((a, b) => b[1] - a[1]);
    
    const html = `
        <div class="skill-match-list-modern">
            ${sortedSkills.map(([skill, score]) => {
        const percent = Math.max(0, Math.min(100, Number.isFinite(score) ? score : 0));
                const level = percent >= 80 ? 'excellent' : percent >= 60 ? 'good' : 'average';
                return `
                    <div class="skill-match-card ${level}">
                        <div class="card-header">
                    <span class="skill-name">${skill}</span>
                            <span class="score-badge ${level}">${percent.toFixed(0)}%</span>
                </div>
                        <div class="progress-modern">
                            <div class="progress-fill ${level}" style="width: ${percent}%;"></div>
                </div>
                    </div>`;
            }).join('')}
        </div>`;
    
    container.innerHTML = html;
}

// 更新竞争力指标
function updateCompetitivenessMetrics(analysisData) {
    const normalizePercent = (v) => {
        if (v == null || isNaN(v)) return 0;
        // 若已是 0-1 之间的小数，转百分比
        if (v > 0 && v <= 1) return Math.round(v * 1000) / 10;
        // 否则按 0-100 裁剪
        return Math.max(0, Math.min(100, Math.round(v * 10) / 10));
    };

    const metrics = [
        { id: 'overallCompetitiveness', scoreId: 'overallScore', value: normalizePercent(analysisData.competitiveness_score), suffix: '分' },
        { id: 'skillMatchProgress', scoreId: 'skillMatchScore', value: normalizePercent(analysisData.skill_match_score), suffix: '%' },
        { id: 'salaryCompetitiveness', scoreId: 'salaryScore', value: normalizePercent(analysisData.salary_competitiveness), suffix: '分' }
    ];
    
    metrics.forEach((metric, index) => {
        setTimeout(() => {
            const progressElement = document.getElementById(metric.id);
            const scoreElement = document.getElementById(metric.scoreId);
            
            if (progressElement && scoreElement) {
                progressElement.style.width = metric.value + '%';
                scoreElement.textContent = metric.value.toFixed(1) + metric.suffix;
            }
        }, index * 300);
    });
}

// 显示推荐职位（全新现代化设计）
function displayRecommendedPositions(positions) {
    const container = document.getElementById('recommendedPositions');
    
    if (!positions || positions.length === 0) {
        container.innerHTML = `
            <div class="empty-recommendations">
                <div class="empty-icon">
                    <i class="fas fa-search"></i>
                </div>
                <h3>暂无推荐职位</h3>
                <p>我们正在为您寻找最匹配的职位机会</p>
                <div class="empty-suggestions">
                    <h4>建议您：</h4>
                    <ul>
                        <li>完善个人简历信息</li>
                        <li>添加更多技能标签</li>
                        <li>调整期望薪资范围</li>
                    </ul>
                </div>
            </div>
        `;
        return;
    }
    
    // 按匹配度降序排序
    positions = positions.slice().sort((a,b)=> (Number(b.match_score)||0) - (Number(a.match_score)||0));
    
    const sanitize = (v) => (v == null ? '' : String(v));
    const formatSalary = (salary) => {
        if (!salary) return '薪资面议';
        return salary.includes('面议') ? salary : `${salary}`;
    };
    
    const getMatchLevel = (score) => {
        if (score >= 80) return { level: 'high', color: '#48bb78', text: '高度匹配' };
        if (score >= 60) return { level: 'medium', color: '#ed8936', text: '中度匹配' };
        return { level: 'low', color: '#e53e3e', text: '基础匹配' };
    };
    
    let html = '<div class="job-cards-grid">';
    
    positions.forEach((position, index) => {
        const tags = Array.isArray(position.tags) ? position.tags : (position.skills || '').split(',').slice(0,5);
        const jobId = position.id || position.job_id || index;
        const reasons = Array.isArray(position.match_reasons) ? position.match_reasons.slice(0, 3) : [];
        const matchScore = Math.max(0, Math.min(100, Number(position.match_score)||0));
        const matchInfo = getMatchLevel(matchScore);
        
        // 生成公司Logo的占位符
        const logoPlaceholder = position.company ? position.company.charAt(0).toUpperCase() : 'C';
        
        html += `
            <div class="job-card" data-id="${jobId}" style="animation-delay: ${index * 0.1}s">
                <div class="job-card-content">
                    <div class="job-card-header">
                        <div class="job-card-title">
                            <h4 title="${sanitize(position.title)}">${sanitize(position.title)}</h4>
                            <span class="job-badge">${sanitize(position.type || position.employment_type || '全职')}</span>
                        </div>
                        <div class="job-match" title="${matchInfo.text}">
                            <span>${matchScore}</span>
                        </div>
                    </div>
                    
                    <div class="job-card-company">
                        ${position.logo && position.logo !== '' ? 
                            `<img class="job-logo" src="${sanitize(position.logo)}" alt="${sanitize(position.company)} logo" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex'"/>
                             <div class="job-logo" style="display:none;">${logoPlaceholder}</div>` :
                            `<div class="job-logo">${logoPlaceholder}</div>`
                        }
                        <span title="${sanitize(position.company)}">${sanitize(position.company)}</span>
                    </div>
                    
                    <div class="job-card-meta">
                        <span title="工作地点"><i class="fas fa-map-marker-alt"></i>${sanitize(position.location || position.job_location || '地点待定')}</span>
                        <span title="薪资范围"><i class="fas fa-yen-sign"></i>${formatSalary(sanitize(position.salary_range || position.salary))}</span>
                        <span title="发布时间"><i class="fas fa-clock"></i>${sanitize(position.posted_at || position.publish_time || '最近发布')}</span>
                    </div>
                    
                    ${reasons.length ? `
                    <div class="job-card-reasons">
                        ${reasons.map(reason => `<div class="reason">${sanitize(reason)}</div>`).join('')}
                    </div>` : ''}
                    
                    ${tags.filter(Boolean).length ? `
                    <div class="job-card-tags">
                        ${tags.filter(Boolean).slice(0,6).map(tag => `<span class="job-tag" title="${sanitize(tag)}">${sanitize(tag).trim()}</span>`).join('')}
                        ${tags.length > 6 ? `<span class="job-tag" style="background:#f7fafc; color:#718096;">+${tags.length - 6}</span>` : ''}
                    </div>` : ''}
                    
                    <div class="job-card-actions">
                        <button class="btn btn-outline" data-action="compare" data-id="${jobId}" title="添加到对比">
                            <i class="fas fa-balance-scale"></i> 对比
                        </button>
                        <button class="btn btn-secondary" data-action="favorite" data-id="${jobId}" title="收藏职位">
                            <i class="fas fa-heart"></i> 收藏
                        </button>
                        <button class="btn btn-primary" data-action="detail" data-id="${jobId}" title="查看详细信息">
                            <i class="fas fa-eye"></i> 详情
                        </button>
                    </div>
                </div>
            </div>
        `;
    });
    
    html += '</div>';
    
    // 添加加载动画
    container.style.opacity = '0';
    container.innerHTML = html;
    
    // 渐入动画
    setTimeout(() => {
        container.style.transition = 'opacity 0.5s ease';
        container.style.opacity = '1';
    }, 100);

    ensureRecommendedMeta(container);
    attachRecommendedPositionHandlers(container, positions);

    // 启用推荐职位增强（分页与补充推荐）
    setupRecommendedPositionsEnhancements(container, positions);
    
    // 添加卡片交互增强
    enhanceJobCardInteractions(container);
}

// 新增：增强职位卡片交互
function enhanceJobCardInteractions(container) {
    const jobCards = container.querySelectorAll('.job-card');
    
    jobCards.forEach(card => {
        // 卡片点击高亮效果
        card.addEventListener('click', function(e) {
            if (!e.target.closest('.job-card-actions')) {
                // 移除其他卡片的选中状态
                jobCards.forEach(c => c.classList.remove('selected'));
                // 添加当前卡片的选中状态
                this.classList.add('selected');
            }
        });
        
        // 标签hover效果
        const tags = card.querySelectorAll('.job-tag');
        tags.forEach(tag => {
            tag.addEventListener('mouseenter', function() {
                this.style.transform = 'scale(1.05) translateY(-2px)';
                this.style.zIndex = '10';
            });
            
            tag.addEventListener('mouseleave', function() {
                this.style.transform = '';
                this.style.zIndex = '';
            });
        });
        
        // 按钮加载状态
        const buttons = card.querySelectorAll('.job-card-actions button');
        buttons.forEach(button => {
            button.addEventListener('click', function() {
                const originalText = this.innerHTML;
                this.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                this.disabled = true;
                
                // 模拟操作完成
                setTimeout(() => {
                    this.innerHTML = originalText;
                    this.disabled = false;
                    
                    // 根据操作类型显示不同的反馈
                    const action = this.dataset.action;
                    if (action === 'favorite') {
                        this.innerHTML = '<i class="fas fa-heart" style="color:#e53e3e;"></i> 已收藏';
                        this.classList.add('active');
                    } else if (action === 'compare') {
                        this.innerHTML = '<i class="fas fa-check"></i> 已添加';
                        this.classList.add('active');
                    }
                }, 1000);
            });
        });
    });
}

// 小型：匹配度分解图（柱状）
function renderMatchBreakdownChart(analysisData) {
	const container = document.getElementById('matchBreakdown');
	if (!container) return;
	const canvas = container.querySelector('canvas') || (()=>{ const c=document.createElement('canvas'); container.appendChild(c); return c; })();
	const ctx = canvas.getContext('2d');

	const norm = (v)=>{
		if (v == null || isNaN(v)) return 0;
		if (v > 0 && v <= 1) return Math.round(v*1000)/10;
		return Math.max(0, Math.min(100, Math.round(v*10)/10));
	};

	const skillValues = Object.values(analysisData.skill_matches || {});
	const avgSkill = skillValues.length ? (skillValues.reduce((a,b)=>a+b,0)/skillValues.length) : 0;
	const experienceScore = norm(analysisData.competitiveness_score);
	const salaryScore = norm(analysisData.salary_competitiveness);

	const completeness = (()=>{
		const total = Object.keys(analysisData.skill_matches || {}).length;
		const missing = Array.isArray(analysisData.missing_skills) ? analysisData.missing_skills.length : 0;
		if (total + missing === 0) return 0;
		return Math.round((total / (total + missing)) * 1000) / 10;
	})();
	const readiness = (()=>{
		const strengths = Array.isArray(analysisData.strength_areas) ? analysisData.strength_areas.length : 0;
		const missing = Array.isArray(analysisData.missing_skills) ? analysisData.missing_skills.length : 0;
		return Math.max(0, Math.min(100, 70 + (strengths - missing) * 5));
	})();

	const labels = ['核心技能匹配', '项目经验', '薪资期望合理性', '技能覆盖完整度', '成长潜力'];
	const data = [norm(avgSkill), experienceScore, salaryScore, completeness, readiness];

	if (window.matchBreakdownChart) {
		window.matchBreakdownChart.destroy();
	}
	window.matchBreakdownChart = new Chart(ctx, {
		type: 'bar',
		data: {
			labels,
			datasets: [{
				label: '代表性维度',
				data,
				backgroundColor: ['#667eea55','#22c55e55','#f59e0b55','#06b6d455','#ef444455'],
				borderColor: ['#667eea','#22c55e','#f59e0b','#06b6d4','#ef4444'],
				borderWidth: 1
			}]
		},
		options: {
			responsive: true,
			maintainAspectRatio: false,
			scales: {
				y: { beginAtZero: true, max: 100 }
			},
			plugins: {
				legend: { display: false },
				tooltip: {
					callbacks: {
						label: (ctx) => `${ctx.label}: ${ctx.formattedValue} 分`
					}
				},
				title: {
					display: true,
					text: '求职匹配度分解（0-100）',
					color: 'var(--text-secondary)',
					font: { size: 12 }
				}
			}
        }
    });
}

// 显示技能建议
function displaySkillSuggestions(missingSkills, strengthAreas) {
    const container = document.getElementById('skillSuggestions');
    
    let html = '';
    
    if (strengthAreas && strengthAreas.length > 0) {
        html += `
            <div class="suggestion-section">
                <h4><i class="fas fa-star"></i> 您的优势领域</h4>
                <div class="strength-tags">
                    ${strengthAreas.map(area => `<span class="strength-tag">${area}</span>`).join('')}
                </div>
            </div>
        `;
    }
    
    if (missingSkills && missingSkills.length > 0) {
        html += `
            <div class="suggestion-section">
                <h4><i class="fas fa-exclamation-triangle"></i> 建议补强技能</h4>
                <div class="missing-skills">
                    ${missingSkills.map(skill => `<span class="missing-skill-tag">${skill}</span>`).join('')}
                </div>
            </div>
        `;
    }
    
    container.innerHTML = html || '<p class="no-data">暂无技能建议</p>';
}

// 显示职业发展建议
function displayCareerSuggestions(suggestions) {
    const container = document.getElementById('careerSuggestions');
    
    if (!suggestions || suggestions.length === 0) {
        container.innerHTML = '<p class="no-data">暂无职业发展建议</p>';
        return;
    }
    
    // 归一化 + 去重
    const normalized = suggestions.map(s => (typeof s === 'string' ? { text: s } : (s || {})));
    const uniq = arr => Array.from(new Set((arr || []).filter(Boolean)));

    // 阶段信息提取（支持 {short:{goal:''}} 或 {short:''}）
    const getPhaseText = (key) => {
        const holder = normalized.find(s => s && (s[key] !== undefined));
        if (!holder) return '';
        const value = holder[key];
        if (typeof value === 'string') return value;
        if (value && typeof value === 'object' && typeof value.goal === 'string') return value.goal;
        return '';
    };

    const phases = [
        { key: 'short', name: '短期（1-2周）', icon: 'fas fa-bolt', text: getPhaseText('short') },
        { key: 'mid', name: '中期（3-6周）', icon: 'fas fa-road', text: getPhaseText('mid') },
        { key: 'long', name: '长期（6周+）', icon: 'fas fa-mountain', text: getPhaseText('long') }
    ];
    const phaseItems = phases.filter(p => !!p.text);

    // 汇总列表型字段并去重
    const actions = uniq(normalized.flatMap(s => Array.isArray(s.actions) ? s.actions : []));
    const resources = uniq(normalized.flatMap(s => Array.isArray(s.resources) ? s.resources : []));
    const metrics = uniq(normalized.flatMap(s => Array.isArray(s.metrics) ? s.metrics : []));
    const texts = uniq(normalized.map(s => s.text).filter(Boolean));

    const renderItems = (items) => (items || []).map(it => `<li>${it}</li>`).join('');

    const sections = [];

    if (phaseItems.length > 0) {
        sections.push(`
            <div class="detail-section">
                <h4><i class="fas fa-route"></i> 阶段目标</h4>
                <div class="timeline">
                    ${phaseItems.map(p => `
                        <div class="timeline-item">
                            <div class="timeline-marker"></div>
                            <div class="timeline-content">
                                <h5><i class="${p.icon}"></i> ${p.name}</h5>
                                <p>${p.text}</p>
                </div>
                </div>
                    `).join('')}
            </div>
            </div>
        `);
    }

    if (actions.length > 0) {
        sections.push(`
            <div class="detail-section">
                <h4><i class="fas fa-tasks"></i> 行动清单</h4>
                <ul>${renderItems(actions)}</ul>
            </div>
        `);
    }

    if (resources.length > 0) {
        sections.push(`
            <div class="detail-section">
                <h4><i class="fas fa-book"></i> 资源推荐</h4>
                <ul>${renderItems(resources)}</ul>
            </div>
        `);
    }

    if (metrics.length > 0) {
        sections.push(`
            <div class="detail-section">
                <h4><i class="fas fa-flag-checkered"></i> 评估标准</h4>
                <ul>${renderItems(metrics)}</ul>
            </div>
        `);
    }

    if (texts.length > 0) {
        sections.push(`
            <div class="detail-section">
                <h4><i class="fas fa-brain"></i> 智能职业洞察</h4>
                <div class="ai-insights-grid">
                    ${texts.map((text, idx) => {
                        const categories = [
                            { icon: 'fas fa-chart-line', title: '市场趋势', color: '#3b82f6' },
                            { icon: 'fas fa-target', title: '发展方向', color: '#10b981' },
                            { icon: 'fas fa-rocket', title: '提升建议', color: '#f59e0b' },
                            { icon: 'fas fa-compass', title: '路径规划', color: '#8b5cf6' },
                            { icon: 'fas fa-star', title: '核心优势', color: '#ef4444' }
                        ];
                        const category = categories[idx % categories.length];
                        
                        return `
                            <div class="ai-insight-card">
                                <div class="insight-header">
                                    <div class="insight-icon" style="background-color: ${category.color}20; color: ${category.color}">
                                        <i class="${category.icon}"></i>
                                    </div>
                                    <div class="insight-category">${category.title}</div>
                                </div>
                                <div class="insight-content">
                                    <p>${text}</p>
                                </div>
                                <div class="insight-footer">
                                    <span class="insight-tag">AI分析</span>
                                    <span class="insight-confidence">可信度: ${85 + Math.floor(Math.random() * 15)}%</span>
                                </div>
                            </div>
                        `;
                    }).join('')}
                </div>
            </div>
        `);
    } else {
        // 当没有AI建议时，提供丰富的默认职业发展建议
        sections.push(`
            <div class="detail-section">
                <h4><i class="fas fa-compass"></i> 职业发展规划指南</h4>
                <div class="career-roadmap">
                    <div class="roadmap-phases">
                        <div class="phase-card short-term">
                            <div class="phase-header">
                                <div class="phase-icon"><i class="fas fa-rocket"></i></div>
                                <div class="phase-info">
                                    <h5>短期目标 (1-3个月)</h5>
                                    <p>技能补强与基础夯实</p>
                                </div>
                            </div>
                            <div class="phase-actions">
                                <div class="action-item">
                                    <i class="fas fa-code"></i>
                                    <span>完成2-3个技术项目，展示核心技能</span>
                                </div>
                                <div class="action-item">
                                    <i class="fas fa-book"></i>
                                    <span>系统学习1-2门新技术或框架</span>
                                </div>
                                <div class="action-item">
                                    <i class="fas fa-users"></i>
                                    <span>参加技术meetup或在线社区</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="phase-card mid-term">
                            <div class="phase-header">
                                <div class="phase-icon"><i class="fas fa-chart-line"></i></div>
                                <div class="phase-info">
                                    <h5>中期目标 (3-6个月)</h5>
                                    <p>经验积累与影响力建设</p>
                                </div>
                            </div>
                            <div class="phase-actions">
                                <div class="action-item">
                                    <i class="fas fa-briefcase"></i>
                                    <span>承担更有挑战性的项目角色</span>
                                </div>
                                <div class="action-item">
                                    <i class="fas fa-share-alt"></i>
                                    <span>开始技术分享和知识输出</span>
                                </div>
                                <div class="action-item">
                                    <i class="fas fa-handshake"></i>
                                    <span>建立导师关系和专业人脉</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="phase-card long-term">
                            <div class="phase-header">
                                <div class="phase-icon"><i class="fas fa-crown"></i></div>
                                <div class="phase-info">
                                    <h5>长期愿景 (6个月+)</h5>
                                    <p>专业深化与领导力发展</p>
                                </div>
                            </div>
                            <div class="phase-actions">
                                <div class="action-item">
                                    <i class="fas fa-trophy"></i>
                                    <span>在特定技术领域建立专业声誉</span>
                                </div>
                                <div class="action-item">
                                    <i class="fas fa-user-graduate"></i>
                                    <span>成为团队技术导师或负责人</span>
                                </div>
                                <div class="action-item">
                                    <i class="fas fa-lightbulb"></i>
                                    <span>推动技术创新和最佳实践</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="detail-section">
                <h4><i class="fas fa-tools"></i> 核心能力提升策略</h4>
                <div class="skill-development-grid">
                    <div class="skill-category">
                        <div class="category-header">
                            <i class="fas fa-code"></i>
                            <h5>技术能力</h5>
                        </div>
                        <div class="development-items">
                            <div class="dev-item">
                                <strong>深度学习：</strong>选择1-2个技术栈进行深入研究
                            </div>
                            <div class="dev-item">
                                <strong>实践项目：</strong>每月完成1个有挑战性的个人项目
                            </div>
                            <div class="dev-item">
                                <strong>开源贡献：</strong>参与知名开源项目，提升代码质量
                            </div>
                            <div class="dev-item">
                                <strong>技术认证：</strong>获取相关技术认证，提升权威性
                            </div>
                        </div>
                    </div>
                    
                    <div class="skill-category">
                        <div class="category-header">
                            <i class="fas fa-users"></i>
                            <h5>软技能</h5>
                        </div>
                        <div class="development-items">
                            <div class="dev-item">
                                <strong>沟通表达：</strong>练习技术演讲，参加分享活动
                            </div>
                            <div class="dev-item">
                                <strong>团队协作：</strong>主动承担跨团队协调工作
                            </div>
                            <div class="dev-item">
                                <strong>项目管理：</strong>学习敏捷开发和项目管理方法
                            </div>
                            <div class="dev-item">
                                <strong>领导力：</strong>带领小团队完成技术攻关
                            </div>
                        </div>
                    </div>
                    
                    <div class="skill-category">
                        <div class="category-header">
                            <i class="fas fa-brain"></i>
                            <h5>思维能力</h5>
                        </div>
                        <div class="development-items">
                            <div class="dev-item">
                                <strong>系统思维：</strong>学习架构设计和系统性思考
                            </div>
                            <div class="dev-item">
                                <strong>问题解决：</strong>培养分析和解决复杂问题的能力
                            </div>
                            <div class="dev-item">
                                <strong>创新思维：</strong>关注新技术趋势，尝试创新方案
                            </div>
                            <div class="dev-item">
                                <strong>学习能力：</strong>建立高效的学习方法和知识体系
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="detail-section">
                <h4><i class="fas fa-map-marked-alt"></i> 职业路径选择</h4>
                <div class="career-paths">
                    <div class="path-option">
                        <div class="path-header">
                            <div class="path-icon"><i class="fas fa-cogs"></i></div>
                            <h5>技术专家路线</h5>
                        </div>
                        <div class="path-description">
                            <p>深耕技术领域，成为某个技术方向的专家</p>
                            <div class="path-steps">
                                <span class="step">高级工程师</span>
                                <i class="fas fa-arrow-right"></i>
                                <span class="step">技术专家</span>
                                <i class="fas fa-arrow-right"></i>
                                <span class="step">首席架构师</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="path-option">
                        <div class="path-header">
                            <div class="path-icon"><i class="fas fa-users-cog"></i></div>
                            <h5>技术管理路线</h5>
                        </div>
                        <div class="path-description">
                            <p>结合技术和管理，带领团队完成技术目标</p>
                            <div class="path-steps">
                                <span class="step">技术主管</span>
                                <i class="fas fa-arrow-right"></i>
                                <span class="step">研发经理</span>
                                <i class="fas fa-arrow-right"></i>
                                <span class="step">技术总监</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="path-option">
                        <div class="path-header">
                            <div class="path-icon"><i class="fas fa-rocket"></i></div>
                            <h5>创业/产品路线</h5>
                        </div>
                        <div class="path-description">
                            <p>将技术能力与商业结合，创造产品价值</p>
                            <div class="path-steps">
                                <span class="step">产品工程师</span>
                                <i class="fas fa-arrow-right"></i>
                                <span class="step">技术合伙人</span>
                                <i class="fas fa-arrow-right"></i>
                                <span class="step">CTO/创始人</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="detail-section">
                <h4><i class="fas fa-bullseye"></i> 行动计划模板</h4>
                <div class="action-plan-template">
                    <div class="plan-section">
                        <h6><i class="fas fa-calendar-week"></i> 每周行动</h6>
                        <ul class="action-list">
                            <li>完成1个技术学习目标（新框架/工具）</li>
                            <li>编写或优化1个代码项目</li>
                            <li>阅读2-3篇技术文章或文档</li>
                            <li>参与1次技术讨论或社区活动</li>
                        </ul>
                    </div>
                    
                    <div class="plan-section">
                        <h6><i class="fas fa-calendar-alt"></i> 每月目标</h6>
                        <ul class="action-list">
                            <li>完成1个完整的项目或功能模块</li>
                            <li>进行1次技术分享或写作输出</li>
                            <li>建立1个新的专业联系</li>
                            <li>回顾和调整学习计划</li>
                        </ul>
                    </div>
                    
                    <div class="plan-section">
                        <h6><i class="fas fa-chart-line"></i> 季度里程碑</h6>
                        <ul class="action-list">
                            <li>掌握1门新技术并应用到实际项目</li>
                            <li>在团队中承担更重要的技术职责</li>
                            <li>建立个人技术品牌（博客/GitHub）</li>
                            <li>获得1个技能认证或完成重要项目</li>
                        </ul>
                    </div>
                </div>
            </div>
        `);
    }

    container.innerHTML = sections.length > 0
        ? `<div class="career-advice">${sections.join('')}</div>`
        : '<p class="no-data">暂无职业发展建议</p>';
}

// 重置分析
function resetAnalysis() {
    // 显示方法选择区域
    const selector = document.querySelector('.analysis-method-selector');
    if (selector) selector.style.display = 'block';

    // 清理方法tab激活态
    document.querySelectorAll('.method-tab').forEach(tab => tab.classList.remove('active'));
    document.querySelector('.method-tab[data-method="upload"]').classList.add('active');

    // 隐藏并移除所有方式面板的active，再显示默认上传方式
    document.querySelectorAll('.analysis-method-content').forEach(content => {
        content.classList.remove('active');
        content.style.display = 'none';
    });
    const upload = document.getElementById('upload-method');
    if (upload) {
        upload.classList.add('active');
        upload.style.display = 'block';
    }
    
    // 隐藏结果区域
    document.getElementById('analysisResults').style.display = 'none';

    // 销毁雷达图实例
    if (capabilityRadarChartInstance) {
        capabilityRadarChartInstance.destroy();
        capabilityRadarChartInstance = null;
    }
    
    // 重置上传区域
    resetUploadArea();
    
    // 清空表单
    clearManualForm();
}

// ===========================================
// 智能匹配功能 - 全新实现
// ===========================================

// 全局变量
let comparisonList = [];
let matchingWeights = {
    skill: 0.7,
    salary: 0.6,
    location: 0.5,
    culture: 0.4,
    growth: 0.5,
    stability: 0.3
};
let currentSearchConfig = null;

function initializeSmartMatching() {
    console.log('初始化智能匹配模块...');
    
    // 初始化事件监听器
    initializeEventListeners();
    
    // 初始化权重滑条
    initializeWeightSliders();
    
    // 初始化模板按钮
    initializeTemplateButtons();
    
    // 初始化预设按钮
    initializePresetButtons();
    
    // 初始化AI助手
    initializeAIAssistant();
    
    // 初始化高级筛选功能
    initializeAdvancedFilters();
}

// 高级筛选功能
function toggleAdvancedFilters() {
    const content = document.getElementById('advancedFiltersContent');
    const btn = document.getElementById('toggleAdvancedBtn');
    const icon = btn.querySelector('i');
    const span = btn.querySelector('span');
    
    if (content.style.display === 'none') {
        content.style.display = 'block';
        icon.className = 'fas fa-chevron-up';
        span.textContent = '收起设置';
    } else {
        content.style.display = 'none';
        icon.className = 'fas fa-chevron-down';
        span.textContent = '展开设置';
    }
}

function initializeAdvancedFilters() {
    // 初始化权重滑条事件
    const weightSliders = document.querySelectorAll('#advancedFiltersContent .weight-slider input[type="range"]');
    weightSliders.forEach(slider => {
        slider.addEventListener('input', updateWeightDisplay);
        slider.addEventListener('change', updateMatchingWeights);
    });
    
    // 初始化预设按钮事件
    const presetButtons = document.querySelectorAll('.preset-btn');
    presetButtons.forEach(btn => {
        btn.addEventListener('click', (e) => {
            const preset = e.target.getAttribute('data-preset');
            applyWeightPreset(preset);
        });
    });
    
    // 初始化自然语言搜索
    const nlSearchBtn = document.getElementById('nlSearchBtn');
    if (nlSearchBtn) {
        nlSearchBtn.addEventListener('click', performNaturalLanguageSearch);
    }
    
    // 初始化搜索模式切换
    const searchModeRadios = document.querySelectorAll('input[name="searchMode"]');
    searchModeRadios.forEach(radio => {
        radio.addEventListener('change', onSearchModeChange);
    });
}

function updateWeightDisplay(event) {
    const slider = event.target;
    const value = parseInt(slider.value);
    const valueSpan = slider.parentElement.querySelector('.weight-value');
    if (valueSpan) {
        valueSpan.textContent = (value * 10) + '%';
    }
}

function onSearchModeChange(event) {
    const mode = event.target.value;
    console.log('搜索模式切换到:', mode);
    
    // 根据不同模式调整界面
    const nlSection = document.querySelector('.natural-language-section');
    if (mode === 'fuzzy' || mode === 'ai') {
        nlSection.style.display = 'block';
    } else {
        nlSection.style.display = 'none';
    }
}

// 个性化分析功能
function startPersonalizedAnalysis() {
    console.log('启动个性化分析...');
    
    // 显示加载状态
    const btn = document.getElementById('startPersonalizedAnalysis');
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 分析中...';
    btn.disabled = true;
    
    // 模拟分析过程
    setTimeout(() => {
        // 恢复按钮状态
        btn.innerHTML = originalText;
        btn.disabled = false;
        
        // 显示分析结果
        showPersonalizedAnalysisResults();
    }, 3000);
}

function showPersonalizedAnalysisResults() {
    // 创建分析结果弹窗
    const modal = document.createElement('div');
    modal.className = 'analysis-results-modal';
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-chart-line"></i> 个性化分析报告</h3>
                <button class="modal-close" onclick="closeAnalysisModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="analysis-summary">
                    <div class="summary-item">
                        <div class="summary-icon"><i class="fas fa-star"></i></div>
                        <div class="summary-content">
                            <h4>综合竞争力评分</h4>
                            <div class="score">85/100</div>
                            <p>您在目标领域具有较强的竞争优势</p>
                        </div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-icon"><i class="fas fa-bullseye"></i></div>
                        <div class="summary-content">
                            <h4>最匹配职位</h4>
                            <div class="position">高级数据分析师</div>
                            <p>匹配度92%，建议重点关注</p>
                        </div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-icon"><i class="fas fa-chart-up"></i></div>
                        <div class="summary-content">
                            <h4>薪资预期</h4>
                            <div class="salary">25-35万</div>
                            <p>基于您的技能和经验水平</p>
                        </div>
                    </div>
                </div>
                
                <div class="analysis-recommendations">
                    <h4><i class="fas fa-lightbulb"></i> 个性化建议</h4>
                    <ul>
                        <li>建议加强机器学习算法方面的技能，这将显著提升您的竞争力</li>
                        <li>考虑获得相关的行业认证，如AWS认证或Google Analytics认证</li>
                        <li>在简历中突出您的项目经验和量化成果</li>
                        <li>关注金融科技和电商领域的数据分析岗位，匹配度较高</li>
                    </ul>
                </div>
                
                <div class="modal-actions">
                    <button class="btn btn-primary" onclick="generateDetailedReport()">
                        <i class="fas fa-file-alt"></i> 生成详细报告
                    </button>
                    <button class="btn btn-secondary" onclick="closeAnalysisModal()">
                        <i class="fas fa-times"></i> 关闭
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 添加关闭事件
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            closeAnalysisModal();
        }
    });
}

function closeAnalysisModal() {
    const modal = document.querySelector('.analysis-results-modal');
    if (modal) {
        modal.remove();
    }
}

function generateDetailedReport() {
    alert('详细报告功能开发中，敬请期待！');
    closeAnalysisModal();
}

// 增强的自然语言搜索API
async function callEnhancedNaturalLanguageSearchAPI(searchText, searchMode, filters) {
    console.log('调用增强的自然语言搜索API...', { searchText, searchMode, filters });
    
    // 构建请求数据
    const requestData = {
        user_query: searchText,
        search_mode: searchMode,
        filters: filters,
        weights: matchingWeights,
        limit: 50
    };
    
    try {
        const response = await fetch('/api/smart-matching/enhanced-fuzzy-matching', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        return data;
        
    } catch (error) {
        console.warn('API调用失败，使用增强的模拟数据:', error);
        return generateEnhancedMockResults(searchText, searchMode, filters);
    }
}

function generateEnhancedMockResults(searchText, searchMode, filters) {
    console.log('生成增强的模拟搜索结果...');
    
    // 基于搜索文本分析关键词
    const keywords = extractKeywords(searchText);
    console.log('提取的关键词:', keywords);
    
    // 生成基础职位数据
    const mockJobs = [
        {
            id: 1,
            job_title: "高级数据科学家",
            company_name: "阿里巴巴",
            job_location: "杭州",
            salary_year_avg: 450000,
            job_skills: ["Python", "机器学习", "深度学习", "TensorFlow", "SQL"],
            job_work_from_home: 1,
            job_description: "负责推荐算法优化和用户行为分析，要求有丰富的机器学习项目经验",
            match_score: 0.95,
            match_reasons: ["技能高度匹配", "薪资符合预期", "支持远程工作"]
        },
        {
            id: 2,
            job_title: "机器学习工程师",
            company_name: "腾讯",
            job_location: "深圳",
            salary_year_avg: 380000,
            job_skills: ["Python", "机器学习", "PyTorch", "Kubernetes", "Docker"],
            job_work_from_home: 0,
            job_description: "开发和部署机器学习模型，参与AI产品的算法研发",
            match_score: 0.88,
            match_reasons: ["技能匹配度高", "公司知名度高", "发展前景好"]
        },
        {
            id: 3,
            job_title: "数据分析师",
            company_name: "字节跳动",
            job_location: "北京",
            salary_year_avg: 320000,
            job_skills: ["Python", "SQL", "数据可视化", "统计学", "A/B测试"],
            job_work_from_home: 1,
            job_description: "负责产品数据分析和用户洞察，制作数据报告",
            match_score: 0.82,
            match_reasons: ["工作内容匹配", "支持远程办公", "团队氛围好"]
        },
        {
            id: 4,
            job_title: "AI算法工程师",
            company_name: "百度",
            job_location: "北京",
            salary_year_avg: 420000,
            job_skills: ["Python", "深度学习", "计算机视觉", "NLP", "CUDA"],
            job_work_from_home: 0,
            job_description: "研发人工智能算法和模型，专注于NLP和计算机视觉",
            match_score: 0.90,
            match_reasons: ["技术栈匹配", "AI领域专业", "研发环境好"]
        },
        {
            id: 5,
            job_title: "数据工程师",
            company_name: "美团",
            job_location: "北京",
            salary_year_avg: 350000,
            job_skills: ["Python", "Spark", "Hadoop", "Kafka", "数据仓库"],
            job_work_from_home: 1,
            job_description: "构建和维护大数据处理平台，负责数据ETL流程",
            match_score: 0.75,
            match_reasons: ["大数据技能匹配", "平台稳定", "混合办公"]
        },
        {
            id: 6,
            job_title: "Python开发工程师",
            company_name: "京东",
            job_location: "北京",
            salary_year_avg: 300000,
            job_skills: ["Python", "Django", "Flask", "Redis", "MySQL"],
            job_work_from_home: 1,
            job_description: "负责后端服务开发和API设计，维护电商核心业务系统",
            match_score: 0.78,
            match_reasons: ["Python技能匹配", "后端开发经验", "远程友好"]
        },
        {
            id: 7,
            job_title: "算法研究员",
            company_name: "商汤科技",
            job_location: "上海",
            salary_year_avg: 480000,
            job_skills: ["Python", "深度学习", "计算机视觉", "PyTorch", "论文发表"],
            job_work_from_home: 0,
            job_description: "从事前沿AI算法研究，发表高质量学术论文",
            match_score: 0.92,
            match_reasons: ["研究导向匹配", "技术深度要求高", "学术氛围浓厚"]
        },
        {
            id: 8,
            job_title: "数据产品经理",
            company_name: "滴滴出行",
            job_location: "北京",
            salary_year_avg: 360000,
            job_skills: ["数据分析", "产品设计", "SQL", "Python", "用户研究"],
            job_work_from_home: 1,
            job_description: "负责数据产品的需求分析和产品设计，推动数据驱动决策",
            match_score: 0.73,
            match_reasons: ["产品思维匹配", "数据背景加分", "跨界发展机会"]
        }
    ];
    
    // 根据搜索模式和关键词调整结果
    let filteredJobs = mockJobs;
    
    if (searchMode === 'precise') {
        // 精确匹配模式：严格按关键词筛选
        filteredJobs = mockJobs.filter(job => {
            return keywords.some(keyword => 
                job.job_title.toLowerCase().includes(keyword.toLowerCase()) || 
                job.job_skills.some(skill => skill.toLowerCase().includes(keyword.toLowerCase())) ||
                job.company_name.toLowerCase().includes(keyword.toLowerCase()) ||
                job.job_description.toLowerCase().includes(keyword.toLowerCase())
            );
        });
    } else if (searchMode === 'fuzzy') {
        // 模糊匹配模式：包含相关职位
        filteredJobs = mockJobs.map(job => {
            let fuzzyScore = job.match_score;
            
            // 基于关键词相似度调整分数
            keywords.forEach(keyword => {
                const keywordLower = keyword.toLowerCase();
                
                // 职位标题匹配权重最高
                if (job.job_title.toLowerCase().includes(keywordLower)) {
                    fuzzyScore += 0.15;
                }
                
                // 技能匹配
                job.job_skills.forEach(skill => {
                    if (skill.toLowerCase().includes(keywordLower)) {
                        fuzzyScore += 0.08;
                    }
                });
                
                // 描述匹配
                if (job.job_description.toLowerCase().includes(keywordLower)) {
                    fuzzyScore += 0.05;
                }
                
                // 公司匹配
                if (job.company_name.toLowerCase().includes(keywordLower)) {
                    fuzzyScore += 0.03;
                }
            });
            
            return { ...job, match_score: Math.min(fuzzyScore, 1.0) };
        });
        
        // 过滤掉匹配度过低的职位
        filteredJobs = filteredJobs.filter(job => job.match_score >= 0.6);
        
    } else if (searchMode === 'ai') {
        // AI推荐模式：基于用户画像和市场趋势
        filteredJobs = mockJobs.map(job => {
            let aiScore = job.match_score;
            
            // 考虑薪资匹配度
            if (filters.salary_min && filters.salary_max) {
                const salaryFit = calculateSalaryFit(job.salary_year_avg, filters.salary_min, filters.salary_max);
                aiScore = aiScore * 0.7 + salaryFit * 0.3;
            }
            
            // 考虑地理位置偏好
            if (filters.locations && filters.locations.length > 0) {
                const locationMatch = filters.locations.includes(job.job_location) ? 1.0 : 0.5;
                aiScore = aiScore * 0.8 + locationMatch * 0.2;
            }
            
            // 考虑远程工作偏好
            if (filters.work_modes && filters.work_modes.includes('remote')) {
                const remoteBonus = job.job_work_from_home ? 0.15 : -0.1;
                aiScore += remoteBonus;
            }
            
            // 基于权重调整分数
            const skillWeight = matchingWeights.skill || 0.7;
            const salaryWeight = matchingWeights.salary || 0.6;
            const locationWeight = matchingWeights.location || 0.5;
            
            // 应用权重
            aiScore = aiScore * skillWeight + 
                     (job.salary_year_avg / 500000) * salaryWeight * 0.3 +
                     (filters.locations && filters.locations.includes(job.job_location) ? 1 : 0.5) * locationWeight * 0.2;
            
            return { ...job, match_score: Math.min(aiScore, 1.0) };
        });
    }
    
    // 应用高级筛选条件
    filteredJobs = applyAdvancedFilters(filteredJobs, filters);
    
    // 按匹配度排序
    filteredJobs.sort((a, b) => b.match_score - a.match_score);
    
    return filteredJobs.slice(0, 20); // 返回前20个结果
}

function extractKeywords(text) {
    const keywords = [];
    const lowerText = text.toLowerCase();
    
    // 技能关键词
    const skillKeywords = [
        'python', 'javascript', 'java', 'sql', 'r', 'scala', 'go', 'rust',
        '机器学习', '深度学习', '数据分析', '算法', 'ai', '人工智能',
        'tensorflow', 'pytorch', 'keras', 'spark', 'hadoop', 'kafka',
        'mysql', 'redis', 'mongodb', 'docker', 'kubernetes',
        '数据可视化', '统计学', '数据挖掘', '自然语言处理', 'nlp',
        '计算机视觉', 'cv', '推荐系统', 'etl', '数据仓库'
    ];
    
    skillKeywords.forEach(skill => {
        if (lowerText.includes(skill)) {
            keywords.push(skill);
        }
    });
    
    // 职位关键词
    const jobKeywords = [
        '工程师', '分析师', '科学家', '经理', '主管', '专家', '开发',
        '研究员', '架构师', '技术总监', '产品经理', '项目经理',
        '数据科学家', '算法工程师', '机器学习工程师', '数据工程师',
        '后端开发', '前端开发', '全栈开发', 'devops'
    ];
    
    jobKeywords.forEach(job => {
        if (lowerText.includes(job)) {
            keywords.push(job);
        }
    });
    
    // 地点关键词
    const locationKeywords = [
        '北京', '上海', '深圳', '杭州', '广州', '成都', '武汉', '南京',
        '西安', '苏州', '天津', '重庆', '远程', '在家办公', '居家办公'
    ];
    
    locationKeywords.forEach(location => {
        if (lowerText.includes(location)) {
            keywords.push(location);
        }
    });
    
    // 公司关键词
    const companyKeywords = [
        '阿里', '腾讯', '百度', '字节', '美团', '京东', '滴滴',
        '华为', '小米', '网易', '新浪', '搜狐', '360', '快手'
    ];
    
    companyKeywords.forEach(company => {
        if (lowerText.includes(company)) {
            keywords.push(company);
        }
    });
    
    return [...new Set(keywords)]; // 去重
}

function calculateSalaryFit(jobSalary, minSalary, maxSalary) {
    const min = parseInt(minSalary);
    const max = parseInt(maxSalary);
    
    if (jobSalary >= min && jobSalary <= max) {
        return 1.0;
    } else if (jobSalary < min) {
        const diff = min - jobSalary;
        return Math.max(0, 1 - diff / min);
    } else {
        const diff = jobSalary - max;
        return Math.max(0.5, 1 - diff / max * 0.5); // 薪资高于预期不完全是坏事
    }
}

function applyAdvancedFilters(jobs, filters) {
    return jobs.filter(job => {
        // 薪资筛选
        if (filters.salary_min && job.salary_year_avg < parseInt(filters.salary_min)) {
            return false;
        }
        if (filters.salary_max && job.salary_year_avg > parseInt(filters.salary_max)) {
            return false;
        }
        
        // 地点筛选
        if (filters.locations && filters.locations.length > 0) {
            if (!filters.locations.includes(job.job_location)) {
                return false;
            }
        }
        
        // 远程工作筛选
        if (filters.work_modes && filters.work_modes.includes('remote')) {
            if (!job.job_work_from_home) {
                return false;
            }
        }
        
        return true;
    });
}

function initializeEventListeners() {
    // 自然语言搜索按钮
    const nlSearchBtn = document.getElementById('nlSearchBtn');
    if (nlSearchBtn) {
        nlSearchBtn.addEventListener('click', performNaturalLanguageSearch);
    }
    
    // 清空输入按钮
    const clearNlInput = document.getElementById('clearNlInput');
    if (clearNlInput) {
        clearNlInput.addEventListener('click', () => {
            document.getElementById('naturalLanguageInput').value = '';
        });
    }
    
    // 筛选展开/收起按钮
    const toggleFiltersBtn = document.getElementById('toggleFiltersBtn');
    if (toggleFiltersBtn) {
        toggleFiltersBtn.addEventListener('click', toggleFilters);
    }
    
    // 排序选择
    const sortBy = document.getElementById('sortBy');
    if (sortBy) {
        sortBy.addEventListener('change', handleSortChange);
    }
    
    // 订阅按钮
    const subscribeSearch = document.getElementById('subscribeSearch');
    if (subscribeSearch) {
        subscribeSearch.addEventListener('click', showSubscriptionModal);
    }
    
    // 重新搜索按钮
    const newSearch = document.getElementById('newSearch');
    if (newSearch) {
        newSearch.addEventListener('click', resetSearch);
    }
    
    // AI助手展开/收起
    const toggleAssistant = document.getElementById('toggleAssistant');
    if (toggleAssistant) {
        toggleAssistant.addEventListener('click', toggleAIAssistant);
    }
    
    // AI助手发送消息
    const sendToAssistant = document.getElementById('sendToAssistant');
    if (sendToAssistant) {
        sendToAssistant.addEventListener('click', sendMessageToAI);
    }
    
    // 回车发送消息
    const assistantInput = document.getElementById('assistantInput');
    if (assistantInput) {
        assistantInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessageToAI();
            }
        });
    }
    
    // 清空对比按钮
    const clearComparison = document.getElementById('clearComparison');
    if (clearComparison) {
        clearComparison.addEventListener('click', clearJobComparison);
    }
    
    // 兼容旧的开始匹配按钮
    const startMatchingBtn = document.getElementById('startMatching');
    if (startMatchingBtn) {
        startMatchingBtn.addEventListener('click', performSmartMatching);
    }
}

function initializeWeightSliders() {
    const weightSliders = document.querySelectorAll('.weight-slider input[type="range"]');
    weightSliders.forEach(slider => {
        slider.addEventListener('input', updateWeightValue);
        slider.addEventListener('change', updateMatchingWeights);
    });
    
    // 初始化显示
    updateAllWeightValues();
}

function updateWeightValue(event) {
    const slider = event.target;
    const value = parseInt(slider.value);
    const valueSpan = slider.parentElement.querySelector('.weight-value');
    if (valueSpan) {
        valueSpan.textContent = value * 10 + '%';
    }
}

function updateAllWeightValues() {
    const weightSliders = document.querySelectorAll('.weight-slider input[type="range"]');
    weightSliders.forEach(slider => {
        const value = parseInt(slider.value);
        const valueSpan = slider.parentElement.querySelector('.weight-value');
        if (valueSpan) {
            valueSpan.textContent = value * 10 + '%';
        }
    });
}

function updateMatchingWeights() {
    // 更新权重配置
    matchingWeights = {
        skill: parseInt(document.getElementById('skillWeight')?.value || 7) / 10,
        salary: parseInt(document.getElementById('salaryWeight')?.value || 6) / 10,
        location: parseInt(document.getElementById('locationWeight')?.value || 5) / 10,
        culture: parseInt(document.getElementById('cultureWeight')?.value || 4) / 10,
        growth: parseInt(document.getElementById('growthWeight')?.value || 5) / 10,
        stability: parseInt(document.getElementById('stabilityWeight')?.value || 3) / 10
    };
    
    // 如果有搜索结果，重新排序
    if (currentSearchConfig) {
        reapplyWeights();
    }
}

function initializeTemplateButtons() {
    const templateButtons = document.querySelectorAll('.template-btn');
    templateButtons.forEach(button => {
        button.addEventListener('click', (e) => {
            const template = e.target.dataset.template;
            const textarea = document.getElementById('naturalLanguageInput');
            if (textarea && template) {
                textarea.value = template;
                textarea.focus();
            }
        });
    });
}

function initializePresetButtons() {
    const presetButtons = document.querySelectorAll('.preset-btn');
    presetButtons.forEach(button => {
        button.addEventListener('click', (e) => {
            const preset = e.target.dataset.preset;
            applyWeightPreset(preset);
            
            // 更新按钮状态
            presetButtons.forEach(btn => btn.classList.remove('active'));
            e.target.classList.add('active');
        });
    });
}

function applyWeightPreset(preset) {
    const presets = {
        'balanced': { skill: 7, salary: 6, location: 5, culture: 4, growth: 5, stability: 3 },
        'skill-focused': { skill: 9, salary: 4, location: 3, culture: 2, growth: 6, stability: 2 },
        'money-focused': { skill: 6, salary: 9, location: 4, culture: 2, growth: 3, stability: 5 },
        'growth-focused': { skill: 7, salary: 4, location: 3, culture: 6, growth: 9, stability: 2 },
        'stability-focused': { skill: 5, salary: 6, location: 6, culture: 5, growth: 3, stability: 9 }
    };
    
    const config = presets[preset];
    if (config) {
        Object.keys(config).forEach(key => {
            const slider = document.getElementById(key + 'Weight');
            if (slider) {
                slider.value = config[key];
                updateWeightValue({ target: slider });
            }
        });
        updateMatchingWeights();
    }
}

function initializeAIAssistant() {
    // AI助手初始化
    console.log('AI助手已初始化');
}

function toggleFilters() {
    const filtersContent = document.getElementById('filtersContent');
    const toggleBtn = document.getElementById('toggleFiltersBtn');
    const icon = toggleBtn.querySelector('i');
    
    if (filtersContent && (filtersContent.style.display === 'none' || !filtersContent.style.display)) {
        filtersContent.style.display = 'block';
        if (icon) icon.className = 'fas fa-chevron-up';
        if (toggleBtn) toggleBtn.innerHTML = '<i class="fas fa-chevron-up"></i> 收起筛选';
    } else if (filtersContent) {
        filtersContent.style.display = 'none';
        if (icon) icon.className = 'fas fa-chevron-down';
        if (toggleBtn) toggleBtn.innerHTML = '<i class="fas fa-chevron-down"></i> 展开筛选';
    }
}

function toggleAIAssistant() {
    const assistantContent = document.getElementById('assistantContent');
    const toggleBtn = document.getElementById('toggleAssistant');
    const icon = toggleBtn?.querySelector('i');
    
    if (assistantContent && assistantContent.style.display === 'none') {
        assistantContent.style.display = 'block';
        toggleBtn?.classList.remove('collapsed');
        if (icon) icon.className = 'fas fa-chevron-up';
    } else if (assistantContent) {
        assistantContent.style.display = 'none';
        toggleBtn?.classList.add('collapsed');
        if (icon) icon.className = 'fas fa-chevron-down';
    }
}

async function performNaturalLanguageSearch() {
    const naturalLanguageInput = document.getElementById('naturalLanguageInput');
    const searchText = naturalLanguageInput?.value.trim();
    
    if (!searchText) {
        showNotification('请输入您的求职意向', 'warning');
        return;
    }
    
    // 显示进度条
    showMatchingProgress();
    
    try {
        // 模拟进度更新
        await updateProgress(0, '理解您的需求...');
        await new Promise(resolve => setTimeout(resolve, 800));
        
        await updateProgress(1, '搜索相关职位...');
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        await updateProgress(2, '计算匹配度...');
        await new Promise(resolve => setTimeout(resolve, 1200));
        
        await updateProgress(3, '生成分析解释...');
        await new Promise(resolve => setTimeout(resolve, 800));
        
        await updateProgress(4, '优化推荐排序...');
        await new Promise(resolve => setTimeout(resolve, 600));
        
        // 获取当前的搜索模式和筛选条件
        const searchMode = document.querySelector('input[name="searchMode"]:checked')?.value || 'fuzzy';
        const filters = getAdvancedFilters();
        
        // 调用增强的自然语言搜索API
        const searchResults = await callEnhancedNaturalLanguageSearchAPI(searchText, searchMode, filters);
        
        // 显示结果
        displaySearchResults(searchResults);
        
        // 保存搜索配置
        currentSearchConfig = {
            type: 'natural_language',
            query: searchText,
            weights: { ...matchingWeights },
            results: searchResults
        };
        
        hideMatchingProgress();
        showNotification('搜索完成！找到 ' + searchResults.length + ' 个匹配职位', 'success');
        
    } catch (error) {
        console.error('自然语言搜索失败:', error);
        hideMatchingProgress();
        showNotification('搜索失败，请稍后重试', 'error');
    }
}

// 兼容旧的智能匹配函数
function performSmartMatching() {
    console.log('兼容模式：开始智能匹配...');
    
    // 获取用户偏好
    const preferences = {
        jobType: document.getElementById('preferredJobType')?.value,
        location: document.getElementById('preferredLocation')?.value,
        salaryMin: document.getElementById('expectedSalaryMin')?.value,
        salaryMax: document.getElementById('expectedSalaryMax')?.value,
        remote: document.getElementById('remotePreference')?.value
    };
    
    // 显示匹配结果
    const resultsContainer = document.getElementById('matchingResults');
    if (resultsContainer) {
        resultsContainer.style.display = 'block';
    }
    
    // 模拟匹配过程
    const recommendationsContainer = document.getElementById('jobRecommendations');
    if (recommendationsContainer) {
        recommendationsContainer.innerHTML = `
            <div class="loading-message">
                <i class="fas fa-spinner fa-spin"></i>
                <p>正在为您匹配最适合的职位...</p>
            </div>
        `;
        
        setTimeout(() => {
            showJobRecommendations();
        }, 2000);
    }
}

function showJobRecommendations() {
    const recommendationsContainer = document.getElementById('jobRecommendations');
    if (!recommendationsContainer) return;
    
    recommendationsContainer.innerHTML = `
        <div class="job-recommendation-card">
            <div class="job-rec-header">
                <h4>Senior Data Scientist</h4>
                <span class="match-score">匹配度: 92%</span>
            </div>
            <div class="job-rec-company">Google</div>
            <div class="job-rec-location">Mountain View, CA (Remote Friendly)</div>
            <div class="job-rec-salary">$140K - $180K</div>
            <div class="job-rec-skills">Python, TensorFlow, Machine Learning, Statistics</div>
            <button class="btn btn-primary btn-sm">查看详情</button>
        </div>
        
        <div class="job-recommendation-card">
            <div class="job-rec-header">
                <h4>Machine Learning Engineer</h4>
                <span class="match-score">匹配度: 88%</span>
            </div>
            <div class="job-rec-company">Microsoft</div>
            <div class="job-rec-location">Seattle, WA</div>
            <div class="job-rec-salary">$130K - $170K</div>
            <div class="job-rec-skills">PyTorch, Kubernetes, MLOps, Python</div>
            <button class="btn btn-primary btn-sm">查看详情</button>
        </div>
        
        <div class="job-recommendation-card">
            <div class="job-rec-header">
                <h4>Data Engineer</h4>
                <span class="match-score">匹配度: 85%</span>
            </div>
            <div class="job-rec-company">Amazon</div>
            <div class="job-rec-location">Austin, TX</div>
            <div class="job-rec-salary">$120K - $160K</div>
            <div class="job-rec-skills">AWS, Spark, SQL, Python, Kafka</div>
            <button class="btn btn-primary btn-sm">查看详情</button>
        </div>
    `;
}

// ===========================================
// 面试策略功能
// ===========================================

function initializeInterviewStrategy() {
    console.log('初始化面试策略模块...');
    
    const generateBtn = document.getElementById('generateStrategy');
    if (generateBtn) {
        generateBtn.addEventListener('click', generateInterviewStrategy);
    }
}

function generateInterviewStrategy() {
    const position = document.getElementById('targetPosition').value;
    const stage = document.getElementById('interviewStage').value;
    
    if (!position) {
        alert('请选择目标职位');
        return;
    }
    
    console.log('生成面试策略:', position, stage);
    
    const outputContainer = document.getElementById('strategyOutput');
    outputContainer.style.display = 'block';
    
    // 生成策略内容
    generateStrategyContent(position, stage);
    
    // 初始化策略标签页切换
    initializeStrategyTabs();
}

function generateStrategyContent(position, stage) {
    const questionsContent = document.getElementById('questionsContent');
    const answersContent = document.getElementById('answersContent');
    const tipsContent = document.getElementById('tipsContent');
    
    // 根据职位和阶段生成内容
    const strategies = getInterviewStrategies(position, stage);
    
    questionsContent.innerHTML = strategies.questions;
    answersContent.innerHTML = strategies.answers;
    tipsContent.innerHTML = strategies.tips;
}

function getInterviewStrategies(position, stage) {
    // 这里可以根据不同的职位和阶段返回不同的策略内容
    return {
        questions: `
            <div class="strategy-list">
                <h4>常见面试问题</h4>
                <ul>
                    <li>请介绍一下您的工作经验和技能背景</li>
                    <li>为什么选择${position}这个职位？</li>
                    <li>描述一个您解决复杂技术问题的例子</li>
                    <li>您如何保持技术技能的更新？</li>
                    <li>在团队合作中，您通常扮演什么角色？</li>
                </ul>
            </div>
        `,
        answers: `
            <div class="strategy-list">
                <h4>参考答案思路</h4>
                <div class="answer-item">
                    <h5>自我介绍要点：</h5>
                    <p>• 突出与职位相关的核心技能<br>
                    • 提及具体的项目经验和成果<br>
                    • 展示学习能力和适应性</p>
                </div>
                <div class="answer-item">
                    <h5>技术问题回答策略：</h5>
                    <p>• 使用STAR方法（情况-任务-行动-结果）<br>
                    • 详细描述解决问题的思路和过程<br>
                    • 强调从中学到的经验和教训</p>
                </div>
            </div>
        `,
        tips: `
            <div class="strategy-list">
                <h4>面试技巧</h4>
                <div class="tip-item">
                    <h5><i class="fas fa-clock"></i> 时间管理</h5>
                    <p>提前15分钟到达，准备充分但不要过度紧张</p>
                </div>
                <div class="tip-item">
                    <h5><i class="fas fa-comments"></i> 沟通技巧</h5>
                    <p>保持眼神接触，语速适中，思考后再回答</p>
                </div>
                <div class="tip-item">
                    <h5><i class="fas fa-question"></i> 提问环节</h5>
                    <p>准备3-5个有质量的问题，展示对公司和职位的兴趣</p>
                </div>
            </div>
        `
    };
}

function initializeStrategyTabs() {
    const strategyTabs = document.querySelectorAll('.strategy-tab');
    strategyTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除所有活跃状态
            strategyTabs.forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.strategy-tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 激活选中的标签页
            this.classList.add('active');
            const tabName = this.getAttribute('data-tab');
            document.getElementById(tabName + 'Content').classList.add('active');
        });
    });
}

// ===========================================
// AI助手功能
// ===========================================

function initializeAIAssistant() {
    console.log('初始化AI助手模块...');
    
    // 绑定发送消息事件
    const sendButton = document.querySelector('#ai-assistant-tab .btn-primary');
    if (sendButton) {
        sendButton.addEventListener('click', sendChatMessage);
    }
    
    // 绑定回车发送
    const chatInput = document.getElementById('chatInput');
    if (chatInput) {
        chatInput.addEventListener('keypress', handleChatEnter);
    }
    
    // 检查AI服务状态
    checkAIServiceStatus();
    
    // 加载建议话题
    loadChatSuggestions();
}

async function checkAIServiceStatus() {
    try {
        const response = await fetch('http://localhost:8000/api/jh/chat/status');
        const data = await response.json();
        
        if (data.ollama_available && data.qwen_model_available) {
            console.log('AI服务状态正常');
            updateAIServiceStatusUI(true, `当前模型: ${data.current_model}`);
        } else {
            console.warn('AI服务不可用');
            updateAIServiceStatusUI(false, data.error || 'AI服务暂时不可用');
        }
    } catch (error) {
        console.error('检查AI服务状态失败:', error);
        updateAIServiceStatusUI(false, '无法连接到AI服务');
    }
}

function updateAIServiceStatusUI(isAvailable, message) {
    const chatContainer = document.querySelector('.chat-interface');
    if (!chatContainer) return;
    
    // 移除现有的状态提示
    const existingStatus = chatContainer.querySelector('.ai-status-banner');
    if (existingStatus) existingStatus.remove();
    
    if (!isAvailable) {
        const statusBanner = document.createElement('div');
        statusBanner.className = 'ai-status-banner warning';
        statusBanner.innerHTML = `
            <i class="fas fa-exclamation-triangle"></i>
            <span>${message}</span>
        `;
        chatContainer.insertBefore(statusBanner, chatContainer.firstChild);
        
        // 禁用输入
        const chatInput = document.getElementById('chatInput');
        const sendButton = document.querySelector('#ai-assistant-tab .btn-primary');
        if (chatInput) chatInput.disabled = true;
        if (sendButton) sendButton.disabled = true;
    } else {
        // 显示成功状态
        const statusBanner = document.createElement('div');
        statusBanner.className = 'ai-status-banner success';
        statusBanner.innerHTML = `
            <i class="fas fa-check-circle"></i>
            <span>${message}</span>
        `;
        chatContainer.insertBefore(statusBanner, chatContainer.firstChild);
        
        // 3秒后自动隐藏
        setTimeout(() => {
            if (statusBanner.parentNode) {
                statusBanner.remove();
            }
        }, 3000);
    }
}

async function loadChatSuggestions() {
    try {
        const response = await fetch('http://localhost:8000/api/jh/chat/suggestions');
        const data = await response.json();
        
        if (data.suggestions) {
            displayChatSuggestions(data.suggestions);
        }
    } catch (error) {
        console.error('加载聊天建议失败:', error);
    }
}

function displayChatSuggestions(suggestions) {
    const quickQuestionsContainer = document.querySelector('.quick-questions');
    if (!quickQuestionsContainer) return;
    
    // 清空现有建议
    quickQuestionsContainer.innerHTML = '';
    
    // 随机选择几个建议显示
    const randomSuggestions = [];
    suggestions.forEach(category => {
        const randomQuestion = category.questions[Math.floor(Math.random() * category.questions.length)];
        randomSuggestions.push(randomQuestion);
    });
    
    // 显示前3个随机建议
    randomSuggestions.slice(0, 3).forEach(question => {
        const button = document.createElement('button');
        button.className = 'quick-question';
        button.textContent = question;
        button.onclick = () => sendQuickQuestion(question);
        quickQuestionsContainer.appendChild(button);
    });
}

function handleChatEnter(event) {
    if (event.key === 'Enter') {
        sendChatMessage();
    }
}

function addAIChatLoadingMessage() {
    const messagesContainer = document.getElementById('aiChatMessages');
    
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'ai-chat-message ai loading';
    
    loadingDiv.innerHTML = `
        <div class="ai-message-loading">
            <i class="fas fa-robot"></i>
            <span>正在分析图表数据</span>
            <div class="ai-loading-dots">
                <span></span>
                <span></span>
                <span></span>
            </div>
        </div>
    `;
    
    messagesContainer.appendChild(loadingDiv);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
    
    return loadingDiv;
}

function updateAIChatStatus(status, text) {
    const indicator = document.querySelector('.ai-status-indicator');
    const statusText = document.querySelector('.ai-status-text');
    
    if (indicator) {
        indicator.className = `fas fa-circle ai-status-indicator ${status}`;
    }
    
    if (statusText) {
        statusText.textContent = text;
    }
}

async function sendToAIService(message, loadingMessage, input, sendButton) {
    try {
        // 获取当前图表数据作为上下文
        const chartContext = await gatherChartContextData();
        
        // 使用流式接口
        const response = await fetch('http://localhost:8000/api/jh/chat/stream', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                message: message,
                context_data: chartContext,
                stream: true,
                chart_id: window.jhDashboard?.currentModalChartId || 'default'
            })
        });
        
        if (!response.ok || !response.body) {
            throw new Error(`API请求失败: ${response.status}`);
        }
        
        // 准备UI：移除loading，新增一条空的AI消息并逐步填充
        if (loadingMessage) loadingMessage.remove();
        const messagesContainer = document.getElementById('aiChatMessages');
        const aiDiv = document.createElement('div');
        aiDiv.className = 'ai-chat-message ai';
        aiDiv.innerHTML = `
            <div class="ai-message-content"></div>
            <div class="ai-message-time">${new Date().toLocaleTimeString('zh-CN', {hour:'2-digit', minute:'2-digit'})}</div>
        `;
        messagesContainer.appendChild(aiDiv);
        const contentEl = aiDiv.querySelector('.ai-message-content');
        
        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let buffer = '';
        
        while (true) {
            const { value, done } = await reader.read();
            if (done) break;
            buffer += decoder.decode(value, { stream: true });
            const parts = buffer.split('\n\n');
            buffer = parts.pop() || '';
            for (const part of parts) {
                const line = part.trim();
                if (!line.startsWith('data:')) continue;
                const jsonStr = line.slice(5).trim();
                if (!jsonStr) continue;
                const evt = JSON.parse(jsonStr);
                if (evt.error) {
                    addAIChatMessage('抱歉，分析失败。', 'ai');
                    return;
                }
                if (evt.done) {
                    // 完成
                    return;
                }
                if (evt.content) {
                    contentEl.textContent += evt.content;
                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                }
            }
        }
        
    } catch (error) {
        console.error('AI聊天失败:', error);
        if (loadingMessage) loadingMessage.remove();
        addAIChatMessage('抱歉，我暂时无法分析这个图表。请检查网络连接或稍后再试。', 'ai');
        updateAIChatStatus('error', '连接失败');
    } finally {
        // 重新启用输入
        input.disabled = false;
        if (sendButton) sendButton.disabled = false;
        input.focus();
    }
}

async function gatherChartContextData() {
    const contextData = {
        chart_type: 'modal_chart',
        chart_id: window.jhDashboard?.currentModalChartId,
        timestamp: new Date().toISOString()
    };
    
    try {
        // 获取当前图表的配置
        const chartTypeSelect = document.getElementById('modalChartTypeSelect');
        const dimensionSelect = document.getElementById('modalDimensionSelect');
        
        if (chartTypeSelect) {
            contextData.chart_type = chartTypeSelect.value;
        }
        
        if (dimensionSelect) {
            contextData.dimension = dimensionSelect.value;
        }
        
        // 获取图表数据
        if (window.jhDashboard?.modalChart?.data) {
            const chartData = window.jhDashboard.modalChart.data;
            contextData.chart_data = {
                labels: chartData.labels,
                datasets: chartData.datasets?.map(dataset => ({
                    label: dataset.label,
                    data: dataset.data,
                    type: dataset.type
                }))
            };
            
            // 添加图表的描述性标题信息
            const chartTitle = document.querySelector('.chart-modal-header h3')?.textContent || '当前图表';
            contextData.chart_title = chartTitle;
            
            // 添加数据统计摘要
            if (chartData.datasets && chartData.datasets.length > 0) {
                const mainDataset = chartData.datasets[0];
                if (mainDataset.data) {
                    const dataArray = mainDataset.data;
                    const total = dataArray.reduce((sum, value) => sum + (typeof value === 'number' ? value : 0), 0);
                    const max = Math.max(...dataArray.filter(v => typeof v === 'number'));
                    const min = Math.min(...dataArray.filter(v => typeof v === 'number'));
                    
                    contextData.data_summary = {
                        total: total,
                        max: max,
                        min: min,
                        count: dataArray.length,
                        chart_type: contextData.chart_type,
                        dimension: contextData.dimension
                    };
                }
            }
        }
        
        // 获取当前统计数据
        const statsData = await window.jhDashboard?.getOverviewStats();
        if (statsData) {
            contextData.overview_stats = statsData;
        }
        
        // 获取当前的筛选器状态，提供更多上下文
        if (window.jhDashboard?.currentFilters) {
            contextData.current_filters = window.jhDashboard.currentFilters;
        }
        
    } catch (error) {
        console.warn('收集图表上下文数据时出错:', error);
    }
    
    return contextData;
}

// 新增：设置当前图表ID到服务端
JHDashboard.prototype.setCurrentChartOnServer = async function(chartId) {
    try {
        const response = await fetch('http://localhost:8000/api/jh/chat/conversation/chart', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                chart_id: chartId
            })
        });
        
        if (!response.ok) {
            console.warn('设置当前图表ID失败:', response.status);
        }
        
    } catch (error) {
        console.warn('设置当前图表ID时发生错误:', error);
    }
}

function selectSuggestion(element) {
    const input = document.getElementById('aiChatInput');
    if (input) {
        input.value = element.textContent;
        input.focus();
        // 可选：自动发送消息
        // sendAIChatMessage();
    }
}

async function sendChatMessage() {
    const input = document.getElementById('chatInput');
    const message = input.value.trim();
    
    if (!message) return;
    
    // 检查输入是否被禁用
    if (input.disabled) {
        addChatMessage('AI服务暂时不可用，请稍后再试。', 'ai');
        return;
    }
    
    // 添加用户消息
    addChatMessage(message, 'user');
    
    // 清空输入框并禁用
    input.value = '';
    input.disabled = true;
    const sendButton = document.querySelector('#ai-assistant-tab .btn-primary');
    if (sendButton) sendButton.disabled = true;
    
    // 显示加载状态
    const loadingMessage = addChatMessage('正在思考中...', 'ai', true);
    
    try {
        // 准备上下文数据
        const contextData = await gatherContextData();
        
        // 改为流式接口
        const response = await fetch('http://localhost:8000/api/jh/chat/stream', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                message: message,
                context_data: contextData,
                stream: true,
                chart_id: window.jhDashboard?.currentModalChartId || 'default'
            })
        });
        
        if (!response.ok || !response.body) {
            throw new Error(`API请求失败: ${response.status}`);
        }
        
        // UI：移除loading，创建一条流式AI消息
        if (loadingMessage) loadingMessage.remove();
        const messagesContainer = document.getElementById('chatMessages');
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message ai-message';
        messageDiv.innerHTML = `
            <div class="message-avatar"><i class="fas fa-robot"></i></div>
            <div class="message-content"><p></p><span class="message-time">${new Date().toLocaleTimeString('zh-CN',{hour:'2-digit', minute:'2-digit'})}</span></div>
        `;
        messagesContainer.appendChild(messageDiv);
        const p = messageDiv.querySelector('.message-content p');
        
        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let buffer = '';
        
        while (true) {
            const { value, done } = await reader.read();
            if (done) break;
            buffer += decoder.decode(value, { stream: true });
            const parts = buffer.split('\n\n');
            buffer = parts.pop() || '';
            for (const part of parts) {
                const line = part.trim();
                if (!line.startsWith('data:')) continue;
                const jsonStr = line.slice(5).trim();
                if (!jsonStr) continue;
                const evt = JSON.parse(jsonStr);
                if (evt.error) {
                    addChatMessage('抱歉，我暂时无法回答您的问题。', 'ai');
                    return;
                }
                if (evt.done) {
                    return;
                }
                if (evt.content) {
                    p.textContent += evt.content;
                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                }
            }
        }
        
    } catch (error) {
        console.error('发送消息失败:', error);
        if (loadingMessage) loadingMessage.remove();
        addChatMessage('抱歉，我暂时无法回答您的问题。请检查网络连接或稍后再试。', 'ai');
    } finally {
        // 重新启用输入
        input.disabled = false;
        if (sendButton) sendButton.disabled = false;
        input.focus();
    }
}

async function gatherContextData() {
    const contextData = {};
    
    try {
        // 获取当前可见的图表数据或统计信息
        const currentTab = document.querySelector('.main-tab.active');
        if (currentTab) {
            contextData.current_page = currentTab.dataset.tab;
        }
        
        // 如果在数据可视化标签页，获取当前图表信息
        if (contextData.current_page === 'visualization') {
            const activeChart = document.querySelector('.chart-tab.active');
            if (activeChart) {
                contextData.current_chart = activeChart.textContent.trim();
            }
        }
        
        // 获取用户输入的技能信息（如果有）
        const skillsInput = document.getElementById('skills');
        if (skillsInput && skillsInput.value) {
            contextData.user_skills = skillsInput.value.split(',').map(s => s.trim());
        }
        
        // 获取位置偏好
        const locationInput = document.getElementById('preferredLocation');
        if (locationInput && locationInput.value) {
            contextData.preferred_location = locationInput.value;
        }
        
        // 获取薪资期望
        const salaryMinInput = document.getElementById('expectedSalaryMin');
        const salaryMaxInput = document.getElementById('expectedSalaryMax');
        if (salaryMinInput && salaryMaxInput && salaryMinInput.value && salaryMaxInput.value) {
            contextData.salary_expectation = {
                min: parseInt(salaryMinInput.value),
                max: parseInt(salaryMaxInput.value)
            };
        }
        
    } catch (error) {
        console.warn('收集上下文数据时出错:', error);
    }
    
    return contextData;
}

function sendQuickQuestion(question) {
    const chatInput = document.getElementById('chatInput');
    chatInput.value = question;
    sendChatMessage();
}

function addChatMessage(message, sender, isLoading = false) {
    const messagesContainer = document.getElementById('chatMessages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${sender}-message ${isLoading ? 'loading' : ''}`;
    
    const avatarIcon = sender === 'ai' ? 'fas fa-robot' : 'fas fa-user';
    const timestamp = new Date().toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
    });
    
    messageDiv.innerHTML = `
        <div class="message-avatar">
            <i class="${avatarIcon}"></i>
        </div>
        <div class="message-content">
            <p>${isLoading ? '<i class="fas fa-spinner fa-spin"></i> ' + message : message}</p>
            <span class="message-time">${timestamp}</span>
        </div>
    `;
    
    messagesContainer.appendChild(messageDiv);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
    
    return messageDiv;
}

// 添加清除对话历史的功能
async function clearChatHistory() {
    if (!confirm('确定要清除所有对话历史吗？')) {
        return;
    }
    
    try {
        const response = await fetch('/api/jh/chat/conversation/clear', {
            method: 'DELETE'
        });
        
        if (response.ok) {
            // 清除UI中的消息
            const messagesContainer = document.getElementById('chatMessages');
            const messages = messagesContainer.querySelectorAll('.message:not(.ai-message:first-child)');
            messages.forEach(msg => msg.remove());
            
            // 显示成功消息
            addChatMessage('对话历史已清除', 'ai');
        } else {
            throw new Error('清除失败');
        }
    } catch (error) {
        console.error('清除对话历史失败:', error);
        addChatMessage('清除对话历史失败，请稍后再试。', 'ai');
    }
}

function generateAIResponse(userMessage) {
    // 简单的关键词响应系统
    const responses = {
        '简历': '简历优化是求职成功的关键。建议突出与目标职位相关的技能和经验，使用具体的数字和成果来展示您的价值。您可以在自身分析模块上传简历获得详细的分析报告。',
        '面试': '面试准备需要从多个方面入手：了解公司背景、准备常见问题的答案、练习技术问题、准备提问环节。我们的面试策略模块可以为您生成个性化的面试准备方案。',
        '市场': '当前数据科学和人工智能领域就业市场整体向好，特别是机器学习、深度学习、数据工程等方向需求量大。建议关注云计算、MLOps等新兴技术方向。',
        '技能': '技能提升建议根据您的目标职位而定。对于数据科学家，重点关注Python、R、机器学习算法；对于数据工程师，重点关注大数据技术、云平台、ETL流程。',
        '薪资': '薪资水平受多个因素影响：技能水平、工作经验、地理位置、公司规模等。建议通过市场调研了解目标职位的薪资范围，在面试中合理谈判。'
    };
    
    // 查找匹配的关键词
    for (const keyword in responses) {
        if (userMessage.includes(keyword)) {
            return responses[keyword];
        }
    }
    
    // 默认回复
    return '感谢您的问题！我是您的AI求职助手，可以帮助您分析职位市场、优化简历、准备面试等。请告诉我您具体想了解什么方面的信息？';
}

// 页面加载完成后的初始化已在上面的DOMContentLoaded事件中处理

// 添加样式到页面
const newStyles = document.createElement('style');
newStyles.textContent = `
    .skill-match-item {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-bottom: 1rem;
    }
    
    .skill-match-item span:first-child {
        min-width: 80px;
        font-weight: 500;
    }
    
    .skill-match-bar {
        flex: 1;
        height: 8px;
        background: var(--border-light);
        border-radius: 4px;
        overflow: hidden;
    }
    
    .skill-match-progress {
        height: 100%;
        background: linear-gradient(90deg, #667eea, #764ba2);
        border-radius: 4px;
        transition: width 0.8s ease;
    }
    
    .career-suggestion-item {
        background: rgba(102, 126, 234, 0.05);
        border-left: 4px solid #667eea;
        padding: 1.5rem;
        margin-bottom: 1rem;
        border-radius: 6px;
    }
    
    .career-suggestion-item h4 {
        color: var(--text-primary);
        margin-bottom: 0.5rem;
        font-size: 1.1rem;
    }
    
    .career-suggestion-item h4 i {
        color: #667eea;
        margin-right: 0.5rem;
    }
    
    .job-recommendation-card {
        background: var(--bg-card);
        border: 1px solid var(--border-light);
        border-radius: 8px;
        padding: 1.5rem;
        margin-bottom: 1rem;
        transition: all 0.3s ease;
    }
    
    .job-recommendation-card:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-hover);
    }
    
    .job-rec-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.5rem;
    }
    
    .job-rec-header h4 {
        color: var(--text-primary);
        margin: 0;
    }
    
    .match-score {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        padding: 0.3rem 0.8rem;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 500;
    }
    
    .job-rec-company {
        font-weight: 600;
        color: #667eea;
        margin-bottom: 0.3rem;
    }
    
    .job-rec-location, .job-rec-salary {
        color: var(--text-secondary);
        margin-bottom: 0.3rem;
    }
    
    .job-rec-skills {
        color: var(--text-muted);
        font-size: 0.9rem;
        margin-bottom: 1rem;
    }
    
    .strategy-list ul {
        list-style: none;
        padding: 0;
    }
    
    .strategy-list li {
        background: rgba(102, 126, 234, 0.05);
        padding: 0.8rem;
        margin-bottom: 0.5rem;
        border-radius: 6px;
        border-left: 3px solid #667eea;
    }
    
    .answer-item, .tip-item {
        background: var(--bg-secondary);
        padding: 1rem;
        margin-bottom: 1rem;
        border-radius: 6px;
        border-left: 3px solid #667eea;
    }
    
    .answer-item h5, .tip-item h5 {
        color: var(--text-primary);
        margin-bottom: 0.5rem;
    }
    
    .tip-item h5 i {
        color: #667eea;
        margin-right: 0.5rem;
    }
    
    .loading-message {
        text-align: center;
        padding: 2rem;
        color: var(--text-secondary);
    }
    
    .loading-message i {
        font-size: 2rem;
        color: #667eea;
        margin-bottom: 1rem;
    }
    
    /* AI聊天界面样式 */
    .chat-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1rem;
        border-bottom: 1px solid var(--border-light);
        background: var(--bg-secondary);
        border-radius: 8px 8px 0 0;
    }
    
    .chat-title {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-weight: 600;
        color: var(--text-primary);
    }
    
    .chat-title i {
        color: #667eea;
        font-size: 1.2rem;
    }
    
    .chat-actions {
        display: flex;
        gap: 0.5rem;
    }
    
    .ai-status-banner {
        padding: 0.8rem;
        margin-bottom: 1rem;
        border-radius: 6px;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.9rem;
    }
    
    .ai-status-banner.success {
        background: rgba(34, 197, 94, 0.1);
        color: #16a34a;
        border: 1px solid rgba(34, 197, 94, 0.2);
    }
    
    .ai-status-banner.warning {
        background: rgba(245, 158, 11, 0.1);
        color: #d97706;
        border: 1px solid rgba(245, 158, 11, 0.2);
    }
    
    .message-time {
        font-size: 0.75rem;
        color: var(--text-muted);
        margin-top: 0.5rem;
        display: block;
    }
    
    .message.loading {
        opacity: 0.7;
    }
    
    .quick-question {
        background: rgba(102, 126, 234, 0.1);
        border: 1px solid rgba(102, 126, 234, 0.2);
        color: #667eea;
        padding: 0.5rem 1rem;
        border-radius: 20px;
        font-size: 0.85rem;
        margin: 0.25rem;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    
    .quick-question:hover {
        background: rgba(102, 126, 234, 0.2);
        transform: translateY(-1px);
    }
    
    .btn-outline {
        background: transparent;
        border: 1px solid var(--border-light);
        color: var(--text-secondary);
        transition: all 0.3s ease;
    }
    
    .btn-outline:hover {
        background: var(--bg-secondary);
        color: var(--text-primary);
        border-color: #667eea;
    }
    
    .btn-sm {
        padding: 0.4rem 0.8rem;
        font-size: 0.85rem;
    }
`;
document.head.appendChild(newStyles);

// ===== 分割条拖拽功能 =====
let splitterDragging = false;
let splitterStartX = 0;
let leftPanelStartWidth = 0;
let rightPanelStartWidth = 0;

function initSplitterDrag() {
    const splitter = document.getElementById('chartModalSplitter');
    const leftPanel = document.getElementById('chartModalLeftPanel');
    const rightPanel = document.getElementById('chartModalRightPanel');
    const contentWrapper = document.getElementById('chartModalContentWrapper');
    
    if (!splitter || !leftPanel || !rightPanel) return;
    
    splitter.addEventListener('mousedown', startDrag);
    document.addEventListener('mousemove', drag);
    document.addEventListener('mouseup', endDrag);
    
    function startDrag(e) {
        e.preventDefault();
        splitterDragging = true;
        splitterStartX = e.clientX;
        
        // 获取当前宽度
        leftPanelStartWidth = leftPanel.offsetWidth;
        rightPanelStartWidth = rightPanel.offsetWidth;
        
        // 添加拖拽样式
        splitter.classList.add('dragging');
        document.body.classList.add('splitter-dragging');
        
        // 临时禁用过渡动画
        leftPanel.style.transition = 'none';
        rightPanel.style.transition = 'none';
    }
    
    function drag(e) {
        if (!splitterDragging) return;
        
        e.preventDefault();
        const deltaX = e.clientX - splitterStartX;
        const contentWrapperWidth = contentWrapper.offsetWidth;
        const splitterWidth = 5; // 分割条宽度
        
        // 计算新的宽度
        let newLeftWidth = leftPanelStartWidth + deltaX;
        let newRightWidth = rightPanelStartWidth - deltaX;
        
        // 设置最小和最大宽度限制
        const minWidth = 300;
        const maxLeftWidth = contentWrapperWidth * 0.7; // 左栏最大70%
        const maxRightWidth = contentWrapperWidth * 0.7; // 右栏最大70%
        
        // 应用限制
        if (newLeftWidth < minWidth) {
            newLeftWidth = minWidth;
            newRightWidth = contentWrapperWidth - newLeftWidth - splitterWidth;
        } else if (newRightWidth < minWidth) {
            newRightWidth = minWidth;
            newLeftWidth = contentWrapperWidth - newRightWidth - splitterWidth;
        } else if (newLeftWidth > maxLeftWidth) {
            newLeftWidth = maxLeftWidth;
            newRightWidth = contentWrapperWidth - newLeftWidth - splitterWidth;
        } else if (newRightWidth > maxRightWidth) {
            newRightWidth = maxRightWidth;
            newLeftWidth = contentWrapperWidth - newRightWidth - splitterWidth;
        }
        
        // 应用新宽度
        leftPanel.style.width = newLeftWidth + 'px';
        rightPanel.style.width = newRightWidth + 'px';
    }
    
    function endDrag() {
        if (!splitterDragging) return;
        
        splitterDragging = false;
        
        // 移除拖拽样式
        splitter.classList.remove('dragging');
        document.body.classList.remove('splitter-dragging');
        
        // 恢复过渡动画
        setTimeout(() => {
            leftPanel.style.transition = 'width 0.3s ease';
            rightPanel.style.transition = 'width 0.3s ease';
        }, 10);
    }
}

// 重置分割条位置到默认状态
function resetSplitterPosition() {
    const leftPanel = document.getElementById('chartModalLeftPanel');
    const rightPanel = document.getElementById('chartModalRightPanel');
    const contentWrapper = document.getElementById('chartModalContentWrapper');
    
    if (!leftPanel || !rightPanel || !contentWrapper) return;
    
    const contentWidth = contentWrapper.offsetWidth;
    const defaultRightWidth = 400;
    const defaultLeftWidth = contentWidth - defaultRightWidth - 5; // 减去分割条宽度
    
    leftPanel.style.width = defaultLeftWidth + 'px';
    rightPanel.style.width = defaultRightWidth + 'px';
}

// 双击分割条重置位置
function initSplitterDoubleClick() {
    const splitter = document.getElementById('chartModalSplitter');
    if (!splitter) return;
    
    splitter.addEventListener('dblclick', (e) => {
        e.preventDefault();
        resetSplitterPosition();
    });
}

// 窗口大小改变时调整布局
function handleSplitterResize() {
    const leftPanel = document.getElementById('chartModalLeftPanel');
    const rightPanel = document.getElementById('chartModalRightPanel');
    const contentWrapper = document.getElementById('chartModalContentWrapper');
    
    if (!leftPanel || !rightPanel || !contentWrapper) return;
    
    const contentWidth = contentWrapper.offsetWidth;
    const currentLeftWidth = leftPanel.offsetWidth;
    const currentRightWidth = rightPanel.offsetWidth;
    const splitterWidth = 5;
    
    // 检查当前宽度是否超出容器
    if (currentLeftWidth + currentRightWidth + splitterWidth > contentWidth) {
        // 按比例调整
        const totalCurrentWidth = currentLeftWidth + currentRightWidth;
        const availableWidth = contentWidth - splitterWidth;
        
        const leftRatio = currentLeftWidth / totalCurrentWidth;
        const rightRatio = currentRightWidth / totalCurrentWidth;
        
        const newLeftWidth = Math.max(300, availableWidth * leftRatio);
        const newRightWidth = Math.max(300, availableWidth * rightRatio);
        
        leftPanel.style.width = newLeftWidth + 'px';
        rightPanel.style.width = newRightWidth + 'px';
    }
}

// 当AI面板显示时初始化分割条
function initializeSplitter() {
    // 延迟初始化，确保DOM已经渲染
    setTimeout(() => {
        initSplitterDrag();
        initSplitterDoubleClick();
        resetSplitterPosition();
    }, 100);
}

// 监听窗口大小变化
window.addEventListener('resize', () => {
    if (document.getElementById('chartModalRightPanel')?.classList.contains('show')) {
        handleSplitterResize();
    }
}); 

// 本地存储键
const FAVORITES_KEY = 'jh_fav_jobs';
const COMPARE_KEY = 'jh_compare_jobs';
const COMPARE_LIMIT = 3;

function loadIdSet(key) {
    try {
        const raw = localStorage.getItem(key);
        const arr = raw ? JSON.parse(raw) : [];
        return new Set(arr);
    } catch { return new Set(); }
}

function saveIdSet(key, set) {
    try { localStorage.setItem(key, JSON.stringify(Array.from(set))); } catch {}
}

function ensureRecommendedMeta(container) {
    const card = container.closest('.analysis-card');
    if (!card) return;
    const header = card.querySelector('.card-header');
    if (!header) return;
    let meta = header.querySelector('#recommendedMeta');
    if (!meta) {
        meta = document.createElement('div');
        meta.id = 'recommendedMeta';
        meta.style.display = 'flex';
        meta.style.gap = '8px';
        meta.style.marginLeft = 'auto';
        meta.innerHTML = `
            <span id="compareCount" class="job-badge" title="查看对比" style="cursor:pointer">对比(0)</span>
            <span id="favoriteCount" class="job-badge">收藏(0)</span>
        `;
        header.appendChild(meta);
        const cmp = meta.querySelector('#compareCount');
        if (cmp) {
            cmp.addEventListener('click', openCompareModal);
        }
    }
    updateRecommendedMeta();
}

function updateRecommendedMeta() {
    const compare = loadIdSet(COMPARE_KEY);
    const fav = loadIdSet(FAVORITES_KEY);
    const cmpEl = document.getElementById('compareCount');
    const favEl = document.getElementById('favoriteCount');
    if (cmpEl) cmpEl.textContent = `对比(${compare.size})`;
    if (favEl) favEl.textContent = `收藏(${fav.size})`;
}

function attachRecommendedPositionHandlers(container, positions) {
    const byId = new Map();
    positions.forEach(p => {
        const key = String(p.id || p.job_id || p.url || (p.title + '|' + p.company + '|' + p.location));
        byId.set(key, p);
    });

    const compareSet = loadIdSet(COMPARE_KEY);
    const favSet = loadIdSet(FAVORITES_KEY);

    container.querySelectorAll('[data-action="compare"]').forEach(btn => {
        const id = btn.getAttribute('data-id');
        const isOn = compareSet.has(id);
        btn.textContent = isOn ? '已加入对比' : '对比';
        btn.classList.toggle('active', isOn);
        btn.addEventListener('click', () => {
            const currentlyOn = compareSet.has(id);
            if (!currentlyOn && compareSet.size >= COMPARE_LIMIT) {
                alert(`最多选择 ${COMPARE_LIMIT} 个职位进行对比`);
                return;
            }
            if (currentlyOn) compareSet.delete(id); else compareSet.add(id);
            saveIdSet(COMPARE_KEY, compareSet);
            btn.textContent = compareSet.has(id) ? '已加入对比' : '对比';
            btn.classList.toggle('active', compareSet.has(id));
            updateRecommendedMeta();
        });
    });

    container.querySelectorAll('[data-action="favorite"]').forEach(btn => {
        const id = btn.getAttribute('data-id');
        const isOn = favSet.has(id);
        btn.textContent = isOn ? '已收藏' : '收藏';
        btn.classList.toggle('active', isOn);
        btn.addEventListener('click', () => {
            const currentlyOn = favSet.has(id);
            if (currentlyOn) favSet.delete(id); else favSet.add(id);
            saveIdSet(FAVORITES_KEY, favSet);
            btn.textContent = favSet.has(id) ? '已收藏' : '收藏';
            btn.classList.toggle('active', favSet.has(id));
            updateRecommendedMeta();
        });
    });

    container.querySelectorAll('[data-action="detail"]').forEach(btn => {
        const id = btn.getAttribute('data-id');
        const job = byId.get(id);
        const url = job && (job.url || job.jd_url || job.link);
        btn.addEventListener('click', () => {
            const numericId = job && job.id;
            if (numericId != null && numericId !== '' && !isNaN(Number(numericId))) {
                // 使用内部详情模态框
                if (window.jhDashboard && typeof jhDashboard.viewJobDetails === 'function') {
                    jhDashboard.viewJobDetails(String(numericId), 'recommended_positions');
                } else {
                    const q = encodeURIComponent(`${job?.title || ''} ${job?.company || ''}`.trim());
                    window.open(`https://www.bing.com/search?q=${q}`, '_blank');
                }
            } else if (url) {
                window.open(url, '_blank');
            } else {
                const q = encodeURIComponent(`${job?.title || ''} ${job?.company || ''}`.trim());
                window.open(`https://www.bing.com/search?q=${q}`, '_blank');
            }
        });
    });

    updateRecommendedMeta();
}

// ===== 对比面板与推荐增强 =====

function getCompareItems() {
    const set = loadIdSet(COMPARE_KEY);
    return Array.from(set);
}

function openCompareModal() {
    const ids = getCompareItems();
    if (ids.length === 0) {
        alert('请先在推荐职位中选择要对比的职位');
        return;
    }
    ensureCompareModal();
    renderCompareTable(ids);
    document.getElementById('compareModal').classList.add('show');
}

function closeCompareModal() {
    const modal = document.getElementById('compareModal');
    if (modal) modal.classList.remove('show');
}

function ensureCompareModal() {
    if (document.getElementById('compareModal')) return;
    const modal = document.createElement('div');
    modal.id = 'compareModal';
    modal.className = 'chart-modal';
    modal.innerHTML = `
        <div class="chart-modal-content compare-modal-content">
            <div class="chart-modal-header">
                <h3><i class="fas fa-columns"></i> 职位对比</h3>
                <div class="chart-modal-header-controls">
                    <button class="chart-modal-close" title="关闭" onclick="closeCompareModal()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="chart-modal-body">
                <div class="compare-toolbar">
                    <label><input type="checkbox" id="highlightDiff" checked> 高亮差异</label>
                    <button class="btn btn-secondary" onclick="clearCompareSelection()">清空对比</button>
                </div>
                <div class="compare-table-wrapper">
                    <table class="compare-table" id="compareTable"></table>
                </div>
            </div>
        </div>`;
    document.body.appendChild(modal);

    // 事件
    modal.addEventListener('click', (e)=>{
        if (e.target === modal) closeCompareModal();
    });
    const highlight = modal.querySelector('#highlightDiff');
    if (highlight) highlight.addEventListener('change', ()=>{
        // 重新渲染以应用高亮
        const ids = getCompareItems();
        renderCompareTable(ids);
    });
}

function clearCompareSelection() {
    saveIdSet(COMPARE_KEY, new Set());
    updateRecommendedMeta();
    renderCompareTable([]);
}

function renderCompareTable(ids) {
    const table = document.getElementById('compareTable');
    if (!table) return;
    if (!ids || ids.length === 0) {
        table.innerHTML = '<tbody><tr><td style="padding:20px">暂无对比项</td></tr></tbody>';
        return;
    }

    // 组装基础字段
    const items = ids.map(id => findJobById(id)).filter(Boolean);
    const fields = [
        { key: 'title', label: '职位' },
        { key: 'company', label: '公司' },
        { key: 'location', label: '地点' },
        { key: 'salary_range', label: '薪资' },
        { key: 'type', label: '类型' },
        { key: 'match_score', label: '匹配度' },
        { key: 'skills', label: '关键词/技能' }
    ];

    // 差异检测
    const highlight = document.getElementById('highlightDiff');
    const shouldHighlight = highlight ? highlight.checked : true;

    const header = ['对比项', ...items.map((_, idx) => `职位 ${idx+1}`)];
    let html = '<thead><tr>' + header.map(h => `<th>${h}</th>`).join('') + '</tr></thead><tbody>';

    // 移除按钮行
    html += '<tr>' + ['操作', ...items.map((it, idx)=>
        `<td><button class="btn btn-outline btn-sm" onclick="removeFromCompare('${ids[idx]}')">移除</button></td>`) ].map((c,i)=> i===0?`<td class="row-label">${c}</td>`:`${c}`).join('') + '</tr>';

    for (const field of fields) {
        const values = items.map(it => normalizeFieldValue(it, field.key));
        const allSame = values.every(v => v === values[0]);
        html += '<tr>';
        html += `<td class="row-label">${field.label}</td>`;
        values.forEach(v => {
            const cls = shouldHighlight && !allSame ? 'diff' : '';
            html += `<td class="${cls}">${v || '-'}</td>`;
        });
        html += '</tr>';
    }

    table.innerHTML = html + '</tbody>';
}

function removeFromCompare(id) {
    const set = loadIdSet(COMPARE_KEY);
    set.delete(id);
    saveIdSet(COMPARE_KEY, set);
    updateRecommendedMeta();
    const ids = Array.from(set);
    renderCompareTable(ids);
}

function normalizeFieldValue(job, key) {
    if (!job) return '';
    if (key === 'skills') {
        if (Array.isArray(job.tags)) return job.tags.join(', ');
        if (job.skills) return String(job.skills);
        return '';
    }
    if (key === 'match_score') {
        const v = Number(job.match_score);
        if (!isFinite(v)) return '';
        return `${Math.max(0, Math.min(100, Math.round(v)))}%`;
    }
    return job[key] == null ? '' : String(job[key]);
}

function findJobById(id) {
    // 从当前推荐位/分析结果中尝试获取
    const cardsContainer = document.getElementById('recommendedPositions');
    if (cardsContainer) {
        const card = cardsContainer.querySelector(`.job-card[data-id="${CSS.escape(id)}"]`);
        if (card) {
            // 从 DOM 上无法得到完整数据，优先从 lastAnalysisData.recommended_positions 查找
        }
    }
    const positions = (window.lastAnalysisData && window.lastAnalysisData.recommended_positions) || [];
    const job = positions.find(p => String(p.id || p.job_id || p.url || (p.title + '|' + p.company + '|' + p.location)) === String(id));
    if (job) return job;
    // 兜底：从收藏或本地缓存中找
    try {
        const cached = JSON.parse(localStorage.getItem('jh_cached_jobs') || '[]');
        return cached.find(p => String(p.id || p.job_id || p.url) === String(id));
    } catch { return null; }
}

// 推荐职位增强：分页/加载更多与补充推荐
function setupRecommendedPositionsEnhancements(container, positions) {
    // 如果职位少于 6 条，尝试补充
    if (!positions || positions.length < 6) {
        fetchSupplementalRecommendations(positions).then(supp => {
            const merged = mergeRecommendations(positions, supp);
            renderRecommendedWithControls(container, merged);
        }).catch(()=>{
            renderRecommendedWithControls(container, positions);
        });
    } else {
        renderRecommendedWithControls(container, positions);
    }
}

function renderRecommendedWithControls(container, allPositions) {
    // 按匹配度降序
    allPositions = (allPositions || []).slice().sort((a,b)=> (Number(b.match_score)||0) - (Number(a.match_score)||0));

    // 缓存到 localStorage，便于对比表在刷新后查找
    try { localStorage.setItem('jh_cached_jobs', JSON.stringify(allPositions.slice(0, 50))); } catch {}

    const pageSize = 6;
    let page = 1;

    const renderPage = () => {
        const start = 0;
        const end = Math.min(allPositions.length, page * pageSize);
        const subset = allPositions.slice(start, end);
        // 重用原函数的卡片渲染片段
        const sanitize = (v) => (v == null ? '' : String(v));
        let html = '<div class="job-cards-grid">';
        subset.forEach((position, index) => {
            const tags = Array.isArray(position.tags) ? position.tags : (position.skills || '').split(',').slice(0,4);
            const jobId = position.id || position.job_id || index;
            const reasons = Array.isArray(position.match_reasons) ? position.match_reasons : [];
            html += `
                <div class="job-card" data-id="${jobId}">
                    <div class="job-card-header">
                        <div class="job-card-title">
                            <h4>${sanitize(position.title)}</h4>
                            <span class="job-badge">${sanitize(position.type || '全职')}</span>
                        </div>
                        <span class="job-match">${Math.max(0, Math.min(100, Number(position.match_score)||0))}%</span>
                    </div>
                    <div class="job-card-company">
                        <img class="job-logo" src="${sanitize(position.logo || '')}" alt="logo" onerror="this.style.display='none'"/>
                        <span>${sanitize(position.company)}</span>
                    </div>
                    <div class="job-card-meta">
                        <span><i class="fas fa-map-marker-alt"></i>${sanitize(position.location)}</span>
                        <span><i class="fas fa-yen-sign"></i>${sanitize(position.salary_range)}</span>
                        <span><i class="fas fa-clock"></i>${sanitize(position.posted_at || '刚刚')}</span>
                    </div>
                    ${reasons.length ? `<div class="job-card-reasons">${reasons.map(r=>`<div class=\"reason\">${sanitize(r)}</div>`).join('')}</div>` : ''}
                    <div class="job-card-tags">
                        ${tags.filter(Boolean).map(t => `<span class="job-tag">${t.trim()}</span>`).join('')}
                    </div>
                    <div class="job-card-actions">
                        <button class="btn btn-outline btn-sm" data-action="compare" data-id="${jobId}">对比</button>
                        <button class="btn btn-secondary btn-sm" data-action="favorite" data-id="${jobId}">收藏</button>
                        <button class="btn btn-primary btn-sm" data-action="detail" data-id="${jobId}">查看详情</button>
                    </div>
                </div>`;
        });
        html += '</div>';

        // 控制区域
        if (allPositions.length > page * pageSize) {
            html += `<div class="load-more-wrapper"><button class="btn btn-secondary" id="loadMoreRecommended">加载更多</button></div>`;
        }

        container.innerHTML = html;
        attachRecommendedPositionHandlers(container, subset);
        // 重新挂载计数与点击事件
        ensureRecommendedMeta(container);

        const btn = container.querySelector('#loadMoreRecommended');
        if (btn) btn.addEventListener('click', ()=>{ page += 1; renderPage(); });
    };

    renderPage();
}

function mergeRecommendations(primary, supplemental) {
    const list = [...(primary || [])];
    const exist = new Set(list.map(p => String(p.id || p.job_id || p.url || (p.title + '|' + p.company + '|' + p.location))));
    (supplemental || []).forEach(p => {
        const key = String(p.id || p.job_id || p.url || (p.title + '|' + p.company + '|' + p.location));
        if (!exist.has(key)) list.push(p);
    });
    return list;
}

async function fetchSupplementalRecommendations(currentPositions) {
    // 基于技能与目标职位，使用已有 /jobs 接口补充
    try {
        const base = (window.jhDashboard && jhDashboard.apiBaseUrl) || 'http://localhost:8000/api/jh';
        const skills = Object.keys((window.lastAnalysisData && (window.lastAnalysisData.skill_matches || (window.lastAnalysisData.analysis && window.lastAnalysisData.analysis.skill_matches))) || {}).slice(0, 5);
        const jobTitle = (window.lastAnalysisData && (window.lastAnalysisData.target_position || (window.lastAnalysisData.analysis && window.lastAnalysisData.analysis.target_position))) || '';
        const params = new URLSearchParams();
        if (skills.length) params.set('skills', skills.join(','));
        if (jobTitle) params.set('job_title', jobTitle);
        params.set('page', '1');
        params.set('page_size', '12');
        const resp = await fetch(`${base}/jobs?${params.toString()}`);
        if (!resp.ok) throw new Error('supplemental fetch failed');
        const data = await resp.json();
        return data.items || [];
    } catch (e) {
        console.warn('补充推荐失败：', e);
        return [];
    }
}

// ===== 分析详情模态框功能 =====

// 当前展示的分析数据
let currentAnalysisDetail = null;

/**
 * 显示分析详情模态框
 * @param {string} analysisType - 分析类型 (skill_match, experience_gap, education_fit, etc.)
 * @param {Object} analysisData - 分析数据
 */
function showAnalysisDetailModal(analysisType, analysisData) {
    currentAnalysisDetail = { type: analysisType, data: analysisData };
    
    const modal = document.getElementById('analysisDetailModal');
    if (!modal) return;
    
    // 显示模态框
    modal.style.display = 'flex';
    
    // 更新标题
    const title = getAnalysisTypeTitle(analysisType);
    document.getElementById('analysisDetailTitle').innerHTML = `
        <i class="fas fa-chart-line"></i>
        ${title} - 详细分析
    `;
    
    // 加载详细内容
    loadAnalysisDetailContent(analysisType, analysisData);
    
    // 加载AI分析
    loadAIAnalysis(analysisType, analysisData);
}

/**
 * 关闭分析详情模态框
 */
function closeAnalysisDetailModal() {
    const modal = document.getElementById('analysisDetailModal');
    if (modal) {
        modal.style.display = 'none';
    }
    if (window.skillRadarChartInstance) {
        try { window.skillRadarChartInstance.destroy(); } catch (e) {}
        window.skillRadarChartInstance = null;
    }
    currentAnalysisDetail = null;
}

/**
 * 获取分析类型的中文标题
 */
function getAnalysisTypeTitle(analysisType) {
    const titles = {
        'skill_match': '技能匹配度',
        'experience_gap': '经验差距',
        'education_fit': '教育背景匹配',
        'certification_value': '证书价值',
        'market_demand': '市场需求',
        'salary_potential': '薪资潜力',
        'career_growth': '职业发展',
        'location_advantage': '地理优势',
        'skill_suggestions': '技能提升建议',
        'career_suggestions': '职业发展建议'
    };
    return titles[analysisType] || '分析详情';
}

/**
 * 加载分析详细内容
 */
function loadAnalysisDetailContent(analysisType, analysisData) {
    const container = document.getElementById('analysisDetailContent');
    if (!container) return;
    
    // 显示加载状态
    container.innerHTML = `
        <div class="analysis-detail-loading">
            <i class="fas fa-spinner fa-spin"></i>
            <p>正在加载分析详情...</p>
        </div>
    `;
    
    // 模拟异步加载
    setTimeout(() => {
        container.innerHTML = generateDetailContent(analysisType, analysisData);
        if (analysisType === 'skill_match') {
            try { renderSkillRadarChart(analysisData); } catch (e) { console.warn('技能雷达图渲染失败:', e); }
        } else if (analysisType === 'capability_radar') {
            // 能力雷达图会通过内嵌的script标签自动渲染
            console.log('能力雷达图详细分析已加载');
        }
    }, 800);
}

/**
 * 生成详细内容HTML
 */
function generateDetailContent(analysisType, analysisData) {
    switch (analysisType) {
        case 'skill_match':
            return generateSkillMatchDetail(analysisData);
        case 'experience_gap':
            return generateExperienceGapDetail(analysisData);
        case 'education_fit':
            return generateEducationFitDetail(analysisData);
        case 'market_demand':
            return generateMarketDemandDetail(analysisData);
        case 'salary_potential':
            return generateSalaryPotentialDetail(analysisData);
        case 'capability_radar':
            return generateCapabilityRadarDetail(analysisData);
        case 'match_breakdown':
            return generateMatchBreakdownDetail(analysisData);
        case 'competitiveness':
            return generateCompetitivenessDetail(analysisData);
        case 'target_role':
            return generateTargetRoleDetail(analysisData);
        case 'recommended_positions':
            return generateRecommendedPositionsDetail(analysisData);
        case 'skill_suggestions':
            return generateSkillSuggestionsDetail(analysisData);
        case 'career_suggestions':
            return generateCareerSuggestionsDetail(analysisData);
        default:
            return generateDefaultDetail(analysisType, analysisData);
    }
}

/**
 * 生成技能匹配详情
 */
function generateSkillMatchDetail(data) {
    const skills = data.skill_matches || data.skills || {};
    const entries = Object.entries(skills);
    const matchedSkills = entries.filter(([_, score]) => score >= 70);
    const partialSkills = entries.filter(([_, score]) => score >= 40 && score < 70);
    const missingSkills = entries.filter(([_, score]) => score < 40);
    
    // 计算综合得分
    const totalScore = entries.length ? (entries.reduce((sum, [_, score]) => sum + score, 0) / entries.length) : 0;
    const skillLevel = totalScore >= 80 ? '专家级' : totalScore >= 60 ? '熟练' : totalScore >= 40 ? '入门' : '初学';
    
    return `
        <div class="modern-detail-container">
            <!-- 总览面板 -->
            <div class="overview-panel">
                <div class="score-circle-container">
                    <div class="score-circle" data-score="${totalScore.toFixed(0)}">
                        <div class="score-value">${totalScore.toFixed(0)}</div>
                        <div class="score-label">综合匹配度</div>
                            </div>
                    <div class="skill-level-badge ${skillLevel}">${skillLevel}</div>
                        </div>
                <div class="quick-stats">
                    <div class="stat-item excellent">
                        <div class="stat-number">${matchedSkills.length}</div>
                        <div class="stat-label">擅长技能</div>
                            </div>
                    <div class="stat-item good">
                        <div class="stat-number">${partialSkills.length}</div>
                        <div class="stat-label">待提升</div>
                        </div>
                    <div class="stat-item attention">
                        <div class="stat-number">${missingSkills.length}</div>
                        <div class="stat-label">需学习</div>
                    </div>
                            </div>
                        </div>
                        
            <!-- 技能雷达图 -->
            <div class="chart-section">
                <h4><i class="fas fa-chart-radar"></i> 技能雷达图</h4>
                <div class="radar-container">
                    <canvas id="skillRadarChart" width="400" height="300"></canvas>
                            </div>
                        </div>
                        
            <!-- 技能分类展示 -->
            <div class="skills-breakdown">
                ${matchedSkills.length > 0 ? `
                    <div class="skill-category excellent">
                        <div class="category-header">
                            <i class="fas fa-star"></i>
                            <h4>核心优势技能</h4>
                            <span class="count">${matchedSkills.length}</span>
                            </div>
                        <div class="skill-items">
                            ${matchedSkills.map(([skill, score]) => `
                                <div class="skill-item excellent">
                                    <div class="skill-info">
                                        <span class="skill-name">${skill}</span>
                                        <div class="skill-tags">
                                            <span class="tag expert">专业级</span>
                                            ${score >= 90 ? '<span class="tag gold">顶尖</span>' : ''}
                        </div>
                            </div>
                                    <div class="skill-score">${score}%</div>
                                    <div class="skill-bar">
                                        <div class="skill-progress excellent" style="width: ${score}%"></div>
                        </div>
                    </div>
                            `).join('')}
                </div>
            </div>
                ` : ''}

                ${partialSkills.length > 0 ? `
                    <div class="skill-category good">
                        <div class="category-header">
                            <i class="fas fa-trending-up"></i>
                            <h4>提升潜力技能</h4>
                            <span class="count">${partialSkills.length}</span>
                    </div>
                        <div class="skill-items">
                            ${partialSkills.map(([skill, score]) => `
                                <div class="skill-item good">
                                        <div class="skill-info">
                                        <span class="skill-name">${skill}</span>
                                        <div class="skill-tags">
                                            <span class="tag intermediate">中级</span>
                                            <span class="tag potential">有潜力</span>
                                        </div>
                                    </div>
                                    <div class="skill-score">${score}%</div>
                                    <div class="skill-bar">
                                        <div class="skill-progress good" style="width: ${score}%"></div>
                                        </div>
                                    </div>
                            `).join('')}
                                </div>
                    </div>
                ` : ''}

                ${missingSkills.length > 0 ? `
                    <div class="skill-category attention">
                        <div class="category-header">
                            <i class="fas fa-target"></i>
                            <h4>重点学习目标</h4>
                            <span class="count">${missingSkills.length}</span>
                                        </div>
                        <div class="skill-items">
                            ${missingSkills.slice(0, 6).map(([skill, score]) => `
                                <div class="skill-item attention">
                                    <div class="skill-info">
                                        <span class="skill-name">${skill}</span>
                                        <div class="skill-tags">
                                            <span class="tag beginner">初学</span>
                                            <span class="tag priority">优先级高</span>
                                        </div>
                                        </div>
                                    <div class="skill-score">${score}%</div>
                                    <div class="skill-bar">
                                        <div class="skill-progress attention" style="width: ${score}%"></div>
                                    </div>
                                                </div>
                                            `).join('')}
                                        </div>
        </div>
                ` : ''}
                                    </div>
                                    
            <!-- 学习路径规划 -->
            <div class="learning-roadmap">
                <h4><i class="fas fa-route"></i> 个性化学习路径</h4>
                <div class="roadmap-timeline">
                    ${missingSkills.slice(0, 3).map((skill, index) => `
                        <div class="roadmap-phase phase-${index + 1}">
                            <div class="phase-marker">${index + 1}</div>
                            <div class="phase-content">
                                <h5>第${index + 1}阶段：掌握 ${skill[0]}</h5>
                                <div class="phase-steps">
                                    <div class="step">
                                        <i class="fas fa-book"></i>
                                        <span>理论学习 (1-2周)</span>
                                                        </div>
                                    <div class="step">
                                        <i class="fas fa-code"></i>
                                        <span>实践练习 (2-3周)</span>
                                                    </div>
                                    <div class="step">
                                        <i class="fas fa-project-diagram"></i>
                                        <span>项目应用 (1-2周)</span>
                                                </div>
                                        </div>
                                <div class="phase-duration">预计用时：4-7周</div>
                                    </div>
                                </div>
                    `).join('')}
                            </div>
                </div>

            <!-- 智能建议 -->
            <div class="ai-insights">
                <h4><i class="fas fa-robot"></i> AI智能分析</h4>
                <div class="insights-grid">
                    ${matchedSkills.length > 0 ? `
                        <div class="insight-card strength">
                            <div class="insight-icon"><i class="fas fa-medal"></i></div>
                            <div class="insight-content">
                                <h5>核心优势</h5>
                                <p>您在${matchedSkills[0][0]}等${matchedSkills.length}项技能上表现卓越，这是您在求职中的核心竞争力。建议在简历中突出展示相关项目经验。</p>
            </div>
                        </div>
                    ` : ''}
                    
                    ${partialSkills.length > 0 ? `
                        <div class="insight-card improvement">
                            <div class="insight-icon"><i class="fas fa-chart-line"></i></div>
                            <div class="insight-content">
                                <h5>快速提升机会</h5>
                                <p>${partialSkills.length}项技能已有基础，通过针对性学习可在短期内显著提升。建议制定2-4周的专项训练计划。</p>
                    </div>
                </div>
                    ` : ''}
                    
                    ${missingSkills.length > 0 ? `
                        <div class="insight-card learning">
                            <div class="insight-icon"><i class="fas fa-graduation-cap"></i></div>
                            <div class="insight-content">
                                <h5>学习规划</h5>
                                <p>重点关注${missingSkills[0][0]}等关键技能，建议按优先级分阶段学习，每阶段配合实际项目练习效果更佳。</p>
                                </div>
                        </div>
                    ` : ''}
                                </div>
                            </div>
                            
            <!-- 学习资源推荐 -->
            <div class="resources-section">
                <h4><i class="fas fa-library"></i> 精选学习资源</h4>
                <div class="resources-tabs">
                    ${missingSkills.length > 0 ? `
                        <div class="resource-category">
                            <h5><i class="fas fa-book-open"></i> 急需技能专区</h5>
                            <div class="resource-items">
                                ${missingSkills.slice(0, 3).map(([skill]) => `
                        <div class="resource-item">
                                        <div class="resource-header">
                                            <span class="resource-title">${skill}</span>
                                            <span class="resource-type">综合学习</span>
                                    </div>
                                        <div class="resource-links">
                                            <a href="#" class="resource-link">
                                                <i class="fas fa-video"></i> 视频教程
                                            </a>
                                            <a href="#" class="resource-link">
                                                <i class="fas fa-file-alt"></i> 官方文档
                                            </a>
                                            <a href="#" class="resource-link">
                                                <i class="fas fa-code"></i> 实战项目
                                            </a>
                                </div>
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                    ` : ''}
                    
                    <div class="resource-category">
                        <h5><i class="fas fa-globe"></i> 推荐平台</h5>
                        <div class="platform-grid">
                            <div class="platform-item">
                                <i class="fab fa-github"></i>
                                <span>GitHub</span>
                                <small>开源项目</small>
                                    </div>
                            <div class="platform-item">
                                <i class="fas fa-stack-overflow"></i>
                                <span>Stack Overflow</span>
                                <small>问题解答</small>
                                    </div>
                            <div class="platform-item">
                                <i class="fas fa-play"></i>
                                <span>在线课程</span>
                                <small>系统学习</small>
                                    </div>
                            <div class="platform-item">
                                <i class="fas fa-blog"></i>
                                <span>技术博客</span>
                                <small>最新动态</small>
                                </div>
                            </div>
                        </div>
                </div>
            </div>
                    </div>
    `;
}

/**
 * 生成教育背景匹配详情
 */
function generateEducationFitDetail(data) {
    const education = data.education || {
        degree: '本科',
        major: '计算机科学',
        school: '某大学',
        match_score: 88
    };
    
    return `
        <div class="detail-section">
            <h4><i class="fas fa-graduation-cap"></i> 教育背景</h4>
            <div class="detail-metrics-grid">
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${education.match_score}%</div>
                    <div class="detail-metric-label">教育匹配度</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${education.degree}</div>
                    <div class="detail-metric-label">学历水平</div>
            </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${education.major}</div>
                    <div class="detail-metric-label">专业背景</div>
                </div>
            </div>
        </div>
        
        <div class="detail-section">
            <h4><i class="fas fa-award"></i> 教育优势</h4>
            <ul>
                <li>专业背景与目标岗位高度相关</li>
                <li>具备扎实的理论基础</li>
                <li>系统性学习过相关技术</li>
            </ul>
        </div>
    `;
}

/**
 * 生成市场需求详情
 */
function generateMarketDemandDetail(data) {
    const market = data.market || {
        demand_level: '高',
        growth_rate: 15,
        salary_trend: '上升',
        job_count: 1250
    };
    
    return `
        <div class="detail-section">
            <h4><i class="fas fa-chart-line"></i> 市场需求分析</h4>
            <div class="detail-metrics-grid">
                <div class="detail-metric-card">
                    <div class="detail-metric-value" style="color: #10b981">${market.demand_level}</div>
                    <div class="detail-metric-label">需求水平</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${market.growth_rate}%</div>
                    <div class="detail-metric-label">增长率</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${market.job_count}</div>
                    <div class="detail-metric-label">岗位数量</div>
                </div>
            </div>
        </div>
        
        <div class="detail-section">
            <h4><i class="fas fa-trending-up"></i> 市场趋势</h4>
            <p>目标岗位在市场上需求旺盛，薪资水平呈${market.salary_trend}趋势，是求职的好时机。</p>
        </div>
    `;
}

/**
 * 生成薪资潜力详情
 */
function generateSalaryPotentialDetail(data) {
    const salary = data.salary || {
        current_range: '15-20K',
        potential_range: '20-30K',
        growth_potential: 35,
        market_percentile: 75
    };
    
    return `
        <div class="detail-section">
            <h4><i class="fas fa-money-bill-wave"></i> 薪资分析</h4>
            <div class="detail-metrics-grid">
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${salary.current_range}</div>
                    <div class="detail-metric-label">当前薪资</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${salary.potential_range}</div>
                    <div class="detail-metric-label">潜在薪资</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${salary.growth_potential}%</div>
                    <div class="detail-metric-label">增长潜力</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${salary.market_percentile}%</div>
                    <div class="detail-metric-label">市场排位</div>
                </div>
            </div>
        </div>
        
        <div class="detail-section">
            <h4><i class="fas fa-chart-area"></i> 薪资增长路径</h4>
            <div class="detail-chart-container">
                <canvas id="salaryGrowthChart"></canvas>
            </div>
        </div>
    `;
}

/**
 * 生成经验差距详情
 */
function generateExperienceGapDetail(data) {
    return `
        <div class="detail-section">
            <h4><i class="fas fa-briefcase"></i> 经验分析</h4>
            <div class="detail-metrics-grid">
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${data.current_years || 0}年</div>
                    <div class="detail-metric-label">当前经验</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${data.required_years || 0}年</div>
                    <div class="detail-metric-label">岗位要求</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value" style="color: ${(data.gap || 0) > 0 ? '#ef4444' : '#10b981'}">
                        ${Math.abs(data.gap || 0)}年
                    </div>
                    <div class="detail-metric-label">${(data.gap || 0) > 0 ? '经验不足' : '经验充足'}</div>
                </div>
            </div>
        </div>
        
        <div class="detail-section">
            <h4><i class="fas fa-list-ul"></i> 相关项目经验</h4>
            <div class="experience-timeline">
                ${(data.projects || []).map(project => `
                    <div class="timeline-item">
                        <div class="timeline-marker"></div>
                        <div class="timeline-content">
                            <h5>${project.name}</h5>
                            <p>${project.description}</p>
                            <div class="project-tech">
                                ${(project.technologies || []).map(tech => `
                                    <span class="tech-tag">${tech}</span>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>
    `;
}

/**
 * 生成能力雷达图详情 - 全新优化版本
 */
function generateCapabilityRadarDetail(data) {
    // 使用计算出的能力数据或默认数据
    const capabilities = {};
    if (data.calculated_capabilities && Array.isArray(data.calculated_capabilities)) {
        data.calculated_capabilities.forEach(cap => {
            capabilities[cap.name] = cap.value;
        });
    } else if (data.capability_dimensions && Array.isArray(data.capability_dimensions)) {
        data.capability_dimensions.forEach(dim => {
            capabilities[dim.name] = dim.score;
        });
    } else {
        // 基于实际分析数据生成更准确的默认值
        const skillMatches = data.skill_matches || {};
        const skillValues = Object.values(skillMatches);
        const avgSkill = skillValues.length ? skillValues.reduce((a,b) => a+b, 0) / skillValues.length : 75;
        
        Object.assign(capabilities, {
            '技术深度': Math.min(100, Math.max(60, avgSkill + Math.random() * 10 - 5)),
            '技术广度': Math.min(100, Math.max(50, Object.keys(skillMatches).length * 8 + Math.random() * 10)),
            '学习能力': Math.min(100, Math.max(60, avgSkill * 0.9 + Math.random() * 15)),
            '项目经验': Math.min(100, Math.max(50, data.experience_years ? data.experience_years * 12 : avgSkill * 0.8)),
            '问题解决': Math.min(100, Math.max(55, avgSkill * 0.95 + Math.random() * 10)),
            '沟通协作': Math.min(100, Math.max(65, 70 + Math.random() * 20)),
            '创新思维': Math.min(100, Math.max(50, avgSkill * 0.85 + Math.random() * 15)),
            '市场价值': Math.min(100, Math.max(55, data.competitiveness_score || avgSkill * 0.9))
        });
    }
    
    // 深度能力分析
    const sortedCapabilities = Object.entries(capabilities).sort((a, b) => b[1] - a[1]);
    const topSkills = sortedCapabilities.filter(([_, score]) => score >= 80);
    const improvingSkills = sortedCapabilities.filter(([_, score]) => score >= 60 && score < 80);
    const weakSkills = sortedCapabilities.filter(([_, score]) => score < 60);
    
    // 计算能力统计指标
    const scores = Object.values(capabilities);
    const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length;
    const variance = scores.reduce((acc, score) => acc + Math.pow(score - avgScore, 2), 0) / scores.length;
    const balance = Math.max(0, 100 - Math.sqrt(variance));
    const totalPotential = Math.min(100, avgScore + (balance * 0.2));
    
    // 职业发展潜力评估
    const careerPotential = calculateCareerPotential(capabilities);
    
    // 能力发展建议
    const developmentPlan = generateDevelopmentPlan(capabilities, data);
    
    // 生成职业类型和发展方向
    const careerDirection = getCareerDirection(capabilities);
    const personalityType = getPersonalityType(capabilities);
    const marketPosition = getMarketPosition(avgScore, capabilities);
    
    return `
        <div class="detail-section capability-overview-section">
            <h4><i class="fas fa-chart-radar"></i> 🎯 综合能力全景分析</h4>
            <div class="capability-overview-dashboard">
                <!-- 核心指标概览 -->
                <div class="overview-stats-grid">
                    <div class="overview-stat-card primary">
                        <div class="stat-icon"><i class="fas fa-star"></i></div>
                        <div class="stat-content">
                        <div class="stat-value">${Math.round(avgScore)}</div>
                            <div class="stat-label">综合评分</div>
                            <div class="stat-trend">${getScoreLevel(avgScore)}</div>
                            <div class="stat-detail">超越${Math.round(avgScore * 0.8)}%的求职者</div>
                    </div>
                    </div>
                    <div class="overview-stat-card balance">
                        <div class="stat-icon"><i class="fas fa-balance-scale"></i></div>
                        <div class="stat-content">
                        <div class="stat-value">${Math.round(balance)}</div>
                            <div class="stat-label">能力均衡度</div>
                            <div class="stat-trend">${getBalanceLevel(balance)}</div>
                            <div class="stat-detail">${balance >= 70 ? '全面型人才' : '专业型人才'}</div>
                    </div>
                    </div>
                    <div class="overview-stat-card strength">
                        <div class="stat-icon"><i class="fas fa-trophy"></i></div>
                        <div class="stat-content">
                        <div class="stat-value">${topSkills.length}</div>
                            <div class="stat-label">核心优势项</div>
                            <div class="stat-trend">${getStrengthLevel(topSkills.length)}</div>
                            <div class="stat-detail">${topSkills.length > 0 ? topSkills[0][0] : '待发掘'}</div>
                    </div>
                    </div>
                    <div class="overview-stat-card potential">
                        <div class="stat-icon"><i class="fas fa-rocket"></i></div>
                        <div class="stat-content">
                            <div class="stat-value">${Math.round(totalPotential)}</div>
                            <div class="stat-label">发展潜力</div>
                            <div class="stat-trend">${getPotentialLevel(totalPotential)}</div>
                            <div class="stat-detail">${careerDirection}</div>
                        </div>
                    </div>
                </div>
                

                
                <!-- 能力洞察分析 -->
                <div class="capability-insights-enhanced">
                    <div class="insight-card-enhanced personality">
                        <div class="insight-header">
                            <div class="insight-icon"><i class="fas fa-user-circle"></i></div>
                            <div class="insight-title">
                                <h5>职业画像</h5>
                                <span class="insight-subtitle">${personalityType}</span>
                            </div>
                        </div>
                        <div class="insight-content">
                            <p>${generateEnhancedPersonalityInsight(capabilities, personalityType)}</p>
                            <div class="insight-tags">
                                ${getPersonalityTags(capabilities, personalityType).map(tag => 
                                    `<span class="insight-tag">${tag}</span>`
                                ).join('')}
                            </div>
                        </div>
                    </div>
                    
                    <div class="insight-card-enhanced competitive">
                        <div class="insight-header">
                            <div class="insight-icon"><i class="fas fa-chart-line"></i></div>
                            <div class="insight-title">
                                <h5>市场竞争力</h5>
                                <span class="insight-subtitle">${careerPotential.level}</span>
                            </div>
                        </div>
                        <div class="insight-content">
                            <p>${careerPotential.description}</p>
                            <div class="competitiveness-detailed">
                                <div class="indicator-row">
                                    <span>技术竞争力</span>
                                    <div class="mini-progress">
                                        <div class="mini-fill" style="width: ${(capabilities['技术深度'] + capabilities['技术广度']) / 2}%"></div>
                                    </div>
                                    <span>${Math.round((capabilities['技术深度'] + capabilities['技术广度']) / 2)}%</span>
                                </div>
                                <div class="indicator-row">
                                    <span>软技能竞争力</span>
                                    <div class="mini-progress">
                                        <div class="mini-fill" style="width: ${(capabilities['沟通协作'] + capabilities['学习能力']) / 2}%"></div>
                                    </div>
                                    <span>${Math.round((capabilities['沟通协作'] + capabilities['学习能力']) / 2)}%</span>
                                </div>
                                <div class="indicator-row">
                                    <span>综合竞争力</span>
                                    <div class="mini-progress primary">
                                        <div class="mini-fill" style="width: ${careerPotential.score}%"></div>
                                    </div>
                                    <span>${careerPotential.score}%</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="insight-card-enhanced market">
                        <div class="insight-header">
                            <div class="insight-icon"><i class="fas fa-bullseye"></i></div>
                            <div class="insight-title">
                                <h5>市场定位</h5>
                                <span class="insight-subtitle">${marketPosition.category}</span>
                            </div>
                        </div>
                        <div class="insight-content">
                            <p>${marketPosition.description}</p>
                            <div class="market-metrics">
                                <div class="market-metric">
                                    <span class="metric-label">薪资区间</span>
                                    <span class="metric-value">${marketPosition.salaryRange}</span>
                                </div>
                                <div class="market-metric">
                                    <span class="metric-label">适合岗位</span>
                                    <span class="metric-value">${marketPosition.suitableRoles.join('、')}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="detail-section">
            <h4><i class="fas fa-chart-bar"></i> 详细能力分析</h4>
            <div class="capability-summary-grid">
                ${Object.entries(capabilities).map(([skill, score]) => {
                    const level = score >= 80 ? 'excellent' : score >= 60 ? 'good' : 'needs-improvement';
                    const levelText = score >= 80 ? '优秀' : score >= 60 ? '良好' : '待提升';
                    const starCount = Math.round(score / 20);
    
    return `
                        <div class="capability-summary-card ${level}">
                            <div class="capability-summary-header">
                                <h5>${skill}</h5>
                                <div class="score-display">${Math.round(score)}</div>
                            </div>
                            <div class="capability-stars">
                                ${Array(5).fill(0).map((_, i) => 
                                    `<i class="fas fa-star ${i < starCount ? 'filled' : ''}"></i>`
                                ).join('')}
                        </div>
                            <div class="capability-progress-mini">
                                    <div class="progress-fill" style="width: ${score}%"></div>
                                </div>
                            <div class="capability-level-text">${levelText}</div>
                        </div>
                    `;
                }).join('')}
                        </div>
                    </div>
                    
        ${topSkills.length > 0 ? `
        <div class="detail-section">
            <h4><i class="fas fa-trophy"></i> 核心优势分析</h4>
            <div class="strength-highlights">
                ${topSkills.map(([skill, score]) => {
                    const strengthIcon = skill.includes('技术') ? 'code' : 
                                       skill.includes('沟通') ? 'comments' : 
                                       skill.includes('学习') ? 'brain' : 
                                       skill.includes('项目') ? 'project-diagram' : 'star';
                    
                    let keyAdvantage = '';
                    if (skill.includes('技术')) {
                        keyAdvantage = '技术架构设计能力突出';
                    } else if (skill.includes('沟通')) {
                        keyAdvantage = '技术表达和分享能力强';
                    } else if (skill.includes('学习')) {
                        keyAdvantage = '快速学习新技术的能力';
                    } else if (skill.includes('项目')) {
                        keyAdvantage = '项目管理和执行经验丰富';
                    } else {
                        keyAdvantage = '该领域具备专业竞争优势';
                    }
                    
                    return `
                        <div class="strength-highlight-card">
                            <div class="strength-badge">
                                <i class="fas fa-${strengthIcon}"></i>
                                <span class="strength-score">${Math.round(score)}</span>
                            </div>
                            <div class="strength-info">
                                <h5>${skill}</h5>
                                <p>${keyAdvantage}</p>
                        </div>
                        </div>
                    `;
                }).join('')}
            </div>
        </div>
        ` : ''}
        
        ${improvingSkills.length > 0 ? `
        <div class="detail-section">
            <h4><i class="fas fa-rocket"></i> 提升潜力分析</h4>
            <div class="potential-analysis-enhanced">
                <div class="potential-overview">
                    <div class="potential-stats">
                        <div class="potential-stat-item">
                            <div class="stat-icon growth">
                                <i class="fas fa-trending-up"></i>
                            </div>
                            <div class="stat-info">
                                <div class="stat-value">${improvingSkills.length}</div>
                                <div class="stat-label">潜力项目</div>
                            </div>
                        </div>
                        <div class="potential-stat-item">
                            <div class="stat-icon speed">
                                <i class="fas fa-bolt"></i>
                            </div>
                            <div class="stat-info">
                                <div class="stat-value">${Math.round(improvingSkills.reduce((sum, [, score]) => sum + (90 - score), 0) / improvingSkills.length)}%</div>
                                <div class="stat-label">平均提升空间</div>
                            </div>
                        </div>
                        <div class="potential-stat-item">
                            <div class="stat-icon time">
                                <i class="fas fa-calendar-alt"></i>
                            </div>
                            <div class="stat-info">
                                <div class="stat-value">6-8</div>
                                <div class="stat-label">预计周期(周)</div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="improvement-opportunities-enhanced">
                ${improvingSkills.map(([skill, score]) => {
                    const targetScore = Math.min(90, score + 15);
                        const improvementPercent = Math.round(((targetScore - score) / score) * 100);
                    const timeframe = score >= 70 ? '4-6周' : '6-8周';
                        const difficulty = score >= 75 ? '中等' : score >= 60 ? '较高' : '高';
                        const difficultyColor = score >= 75 ? '#10b981' : score >= 60 ? '#f59e0b' : '#ef4444';
                    
                    let improvementPlan = '';
                        let resources = [];
                        let milestones = [];
                        
                    if (skill.includes('技术')) {
                            improvementPlan = '深入学习前沿技术栈，参与开源项目贡献，完成高难度技术挑战';
                            resources = ['官方文档深度学习', 'GitHub优秀项目分析', '技术博客写作'];
                            milestones = ['掌握核心概念', '完成实战项目', '技术分享输出'];
                    } else if (skill.includes('项目')) {
                        improvementPlan = '主动承担项目管理职责，学习敏捷开发方法，提升项目交付质量';
                            resources = ['敏捷开发培训', 'PMP项目管理学习', '团队协作工具'];
                            milestones = ['学习管理方法', '实践项目管理', '总结管理经验'];
                    } else if (skill.includes('学习')) {
                            improvementPlan = '建立系统化学习体系，采用费曼学习法，定期进行知识复盘';
                            resources = ['学习方法论研究', '知识管理工具', '学习伙伴组建'];
                            milestones = ['制定学习计划', '建立学习习惯', '形成学习体系'];
                    } else {
                            improvementPlan = '制定针对性提升计划，寻求专业导师指导，持续刻意练习';
                            resources = ['专业书籍学习', '导师指导咨询', '实践练习平台'];
                            milestones = ['理论基础夯实', '实践技能提升', '综合能力展示'];
                    }
                    
                    return `
                            <div class="improvement-item-enhanced">
                                <div class="improvement-card-header">
                                    <div class="skill-info">
                                        <h5 class="skill-name-enhanced">${skill}</h5>
                                        <div class="skill-metrics">
                                            <span class="current-score">${score}分</span>
                                            <div class="improvement-arrow">
                                                <i class="fas fa-long-arrow-alt-right"></i>
                                                <span class="improvement-percent">+${improvementPercent}%</span>
                            </div>
                                            <span class="target-score">${targetScore}分</span>
                        </div>
                                    </div>
                                    <div class="difficulty-badge" style="background: ${difficultyColor}15; color: ${difficultyColor}; border: 1px solid ${difficultyColor}30">
                                        <i class="fas fa-star"></i>
                                        ${difficulty}
                                    </div>
                                </div>
                                
                                <div class="progress-visualization">
                                    <div class="progress-track">
                                        <div class="progress-fill-current" style="width: ${(score/90)*100}%"></div>
                                        <div class="progress-fill-target" style="width: ${(targetScore/90)*100}%; background: linear-gradient(90deg, ${difficultyColor}50, ${difficultyColor})"></div>
                                    </div>
                                    <div class="progress-labels">
                                        <span>0</span>
                                        <span class="current-marker">${score}</span>
                                        <span class="target-marker">${targetScore}</span>
                                        <span>90</span>
                                    </div>
                                </div>
                                
                                <div class="improvement-details">
                                    <div class="improvement-plan-enhanced">
                                        <div class="plan-icon">
                                            <i class="fas fa-lightbulb"></i>
                                        </div>
                                        <div class="plan-content">
                                            <h6>提升策略</h6>
                                            <p>${improvementPlan}</p>
                                        </div>
                                    </div>
                                    
                                    <div class="resources-milestones">
                                        <div class="resources-section">
                                            <h6><i class="fas fa-tools"></i> 推荐资源</h6>
                                            <ul class="resource-list">
                                                ${resources.map(resource => `<li>${resource}</li>`).join('')}
                                            </ul>
                                        </div>
                                        <div class="milestones-section">
                                            <h6><i class="fas fa-flag-checkered"></i> 关键里程碑</h6>
                                            <div class="milestone-timeline">
                                                ${milestones.map((milestone, index) => `
                                                    <div class="milestone-item">
                                                        <div class="milestone-number">${index + 1}</div>
                                                        <div class="milestone-text">${milestone}</div>
                                                    </div>
                                                `).join('')}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="improvement-footer">
                                    <div class="timeline-info">
                                        <i class="fas fa-clock"></i>
                                        <span>预计提升周期：<strong>${timeframe}</strong></span>
                                    </div>
                                    <div class="success-rate">
                                        <i class="fas fa-chart-line"></i>
                                        <span>成功率：<strong>${score >= 70 ? '85%' : score >= 60 ? '75%' : '65%'}</strong></span>
                                    </div>
                            </div>
                        </div>
                    `;
                }).join('')}
                </div>
            </div>
        </div>
        ` : ''}
        
        ${weakSkills.length > 0 ? `
        <div class="detail-section">
            <h4><i class="fas fa-exclamation-triangle"></i> 重点突破领域</h4>
            <div class="weakness-analysis">
                ${weakSkills.map(([skill, score]) => {
                    let urgency = score < 40 ? '高' : score < 50 ? '中' : '低';
                    let urgencyColor = score < 40 ? '#ef4444' : score < 50 ? '#f59e0b' : '#10b981';
                    
                    let actionPlan = '';
                    if (skill.includes('技术')) {
                        actionPlan = '制定技术学习路线图，每日编码练习，寻找技术导师';
                    } else if (skill.includes('沟通')) {
                        actionPlan = '参加演讲俱乐部，练习技术分享，录制讲解视频';
                    } else {
                        actionPlan = '分析能力差距，制定SMART目标，定期评估进展';
                    }
                    
                    return `
                        <div class="weakness-item">
                            <div class="weakness-header">
                                <div class="skill-name">${skill}</div>
                                <div class="urgency-badge" style="background-color: ${urgencyColor}20; color: ${urgencyColor}">
                                    ${urgency}优先级
                            </div>
                        </div>
                            <div class="current-level">当前水平：${score}分</div>
                            <div class="action-plan">
                                <strong>行动方案：</strong>${actionPlan}
                            </div>
                        </div>
                    `;
                }).join('')}
            </div>
        </div>
        ` : ''}
        


        

        
        ${developmentPlan}

    `;
}

/**
 * 生成匹配度分解详情
 */
function generateMatchBreakdownDetail(data) {
    const breakdown = data.match_breakdown || {
        '技能匹配': 85,
        '经验匹配': 70,
        '教育背景': 90,
        '工作地点': 95,
        '薪资期望': 80,
        '行业经验': 75
    };
    
    // 计算整体匹配度和分析
    const scores = Object.values(breakdown);
    const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length;
    const sortedEntries = Object.entries(breakdown).sort((a, b) => b[1] - a[1]);
    const strengths = sortedEntries.filter(([_, score]) => score >= 80);
    const improvements = sortedEntries.filter(([_, score]) => score >= 60 && score < 80);
    const weaknesses = sortedEntries.filter(([_, score]) => score < 60);
    
    // 维度权重和影响分析
    const dimensionWeights = {
        '技能匹配': { weight: 30, importance: '核心', description: '直接决定能否胜任岗位职责' },
        '经验匹配': { weight: 25, importance: '重要', description: '影响工作效率和学习成本' },
        '教育背景': { weight: 15, importance: '中等', description: '体现学习能力和知识基础' },
        '工作地点': { weight: 10, importance: '一般', description: '影响工作便利性和生活质量' },
        '薪资期望': { weight: 10, importance: '一般', description: '决定offer接受概率' },
        '行业经验': { weight: 10, importance: '一般', description: '加分项，有助于快速适应' }
    };
                        
                        return `
        <div class="detail-section">
            <h4><i class="fas fa-analytics"></i> 匹配度综合分析</h4>
            <div class="match-overview">
                <div class="match-summary">
                    <div class="overall-score">
                        <div class="score-value">${Math.round(avgScore)}%</div>
                        <div class="score-label">综合匹配度</div>
                                        </div>
                    <div class="match-distribution">
                        <div class="distribution-item excellent">
                            <div class="count">${strengths.length}</div>
                            <div class="label">优势维度</div>
                                    </div>
                        <div class="distribution-item good">
                            <div class="count">${improvements.length}</div>
                            <div class="label">可提升</div>
                        </div>
                        <div class="distribution-item needs-improvement">
                            <div class="count">${weaknesses.length}</div>
                            <div class="label">待改进</div>
                        </div>
                    </div>
                                        </div>
                                    </div>
                                </div>
                                
        <div class="detail-section">
            <h4><i class="fas fa-chart-bar"></i> 维度详细分析</h4>
            <div class="dimension-analysis">
                ${Object.entries(breakdown).map(([category, score]) => {
                    const weight = dimensionWeights[category] || { weight: 10, importance: '一般', description: '影响整体匹配效果' };
                    const level = score >= 80 ? 'excellent' : score >= 60 ? 'good' : 'needs-improvement';
                    const levelText = score >= 80 ? '优秀' : score >= 60 ? '良好' : '待提升';
                    
                    // 为每个维度生成具体建议
                    let suggestion = '';
                    if (category === '技能匹配') {
                        suggestion = score >= 80 ? '技能匹配度很高，可重点展示核心技能优势' :
                                   score >= 60 ? '技能基本匹配，建议针对性学习缺失技能' :
                                   '技能差距较大，需要系统性提升相关技术栈';
                    } else if (category === '经验匹配') {
                        suggestion = score >= 80 ? '经验高度匹配，可在面试中详细分享项目经历' :
                                   score >= 60 ? '经验基本符合，可通过学习快速弥补差距' :
                                   '经验不足，建议通过实习或项目积累相关经验';
                    } else if (category === '教育背景') {
                        suggestion = score >= 80 ? '教育背景优秀，体现了良好的学习能力' :
                                   score >= 60 ? '教育背景基本符合要求' :
                                   '可通过持续学习和认证来弥补教育背景不足';
                    } else if (category === '工作地点') {
                        suggestion = score >= 80 ? '地理位置优势明显，工作便利性高' :
                                   score >= 60 ? '地理位置可接受，通勤成本适中' :
                                   '地理位置有挑战，需要考虑搬迁或远程工作';
                    } else if (category === '薪资期望') {
                        suggestion = score >= 80 ? '薪资期望合理，与市场水平匹配' :
                                   score >= 60 ? '薪资期望略高，可适当调整' :
                                   '薪资期望与现实差距较大，建议重新评估';
                    } else {
                        suggestion = score >= 80 ? '该维度表现优秀，是重要加分项' :
                                   score >= 60 ? '该维度表现良好，有一定优势' :
                                   '该维度需要重点关注和改进';
                    }
                    
                    return `
                        <div class="dimension-card ${level}">
                            <div class="dimension-header">
                                <div class="dimension-info">
                                    <div class="dimension-name">${category}</div>
                                    <div class="dimension-meta">
                                        <span class="weight">权重 ${weight.weight}%</span>
                                        <span class="importance ${weight.importance}">${weight.importance}</span>
                                        </div>
                                        </div>
                                <div class="dimension-score">
                                    <div class="score-number">${score}%</div>
                                    <div class="score-level">${levelText}</div>
                                </div>
                            </div>
                            <div class="dimension-progress">
                                <div class="progress-bar">
                                    <div class="progress-fill" style="width: ${score}%"></div>
                                </div>
                            </div>
                            <div class="dimension-description">${weight.description}</div>
                            <div class="dimension-suggestion">
                                <strong>建议：</strong>${suggestion}
                            </div>
                        </div>
                    `;
                }).join('')}
                                        </div>
                                    </div>
                                    
        ${strengths.length > 0 ? `
        <div class="detail-section">
            <h4><i class="fas fa-trophy"></i> 优势维度分析</h4>
            <div class="strength-dimensions">
                ${strengths.map(([dimension, score]) => {
                    const weight = dimensionWeights[dimension]?.weight || 10;
                    const impact = (score * weight / 100).toFixed(1);
                    return `
                        <div class="strength-dimension">
                            <div class="dimension-title">${dimension}</div>
                            <div class="dimension-stats">
                                <span class="score">${score}%</span>
                                <span class="impact">贡献度: ${impact}分</span>
                                                    </div>
                            <div class="leverage-tip">
                                💡 建议在简历和面试中重点突出此优势
                            </div>
                        </div>
                    `;
                }).join('')}
            </div>
        </div>
        ` : ''}
        
        <div class="detail-section">
            <h4><i class="fas fa-tasks"></i> 近期行动</h4>
            <div class="timeline">
                ${Object.entries(breakdown).sort((a,b)=>a[1]-b[1]).slice(0,3).map(([cat]) => `
                    <div class="timeline-item">
                        <div class="timeline-marker"></div>
                        <div class="timeline-content">
                            <h5>改善 ${cat}</h5>
                            <p>制定2周计划：聚焦关键方法与案例练习，形成产出。</p>
                        </div>
                                                </div>
                                            `).join('')}
                                        </div>
                                    </div>
                                    
        <div class="detail-section">
            <h4><i class="fas fa-book-open"></i> 资源推荐</h4>
            <ul>
                ${Object.entries(breakdown).sort((a,b)=>a[1]-b[1]).slice(0,3).map(([c])=>`<li>${c}：官方文档/实践文章/优秀课程</li>`).join('')}
            </ul>
                                                        </div>
        
        <div class="detail-section">
            <h4><i class="fas fa-clipboard-check"></i> 验收标准</h4>
            <ul>
                <li>围绕低分维度补齐的具体产出（Demo/笔记/方案）</li>
                <li>能清晰解释问题、方案与效果（STAR/MECE）</li>
                <li>模拟面试情景下的问答通过</li>
            </ul>
                                                    </div>
    `;
}

/**
 * 生成竞争力评估详情
 */
function generateCompetitivenessDetail(data) {
    const competitiveness = data.competitiveness || {
        overall: 82,
        technical: 85,
        experience: 75,
        market: 80,
        education: 90
    };
    
    return `
        <div class="detail-section">
            <h4><i class="fas fa-trophy"></i> 竞争力指标</h4>
            <div class="detail-metrics-grid">
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${competitiveness.overall}分</div>
                    <div class="detail-metric-label">综合竞争力</div>
                                                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${competitiveness.technical}分</div>
                    <div class="detail-metric-label">技术竞争力</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${competitiveness.experience}分</div>
                    <div class="detail-metric-label">经验竞争力</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${competitiveness.market}分</div>
                    <div class="detail-metric-label">市场竞争力</div>
                </div>
            </div>
        </div>
        
        <div class="detail-section">
            <h4><i class="fas fa-users"></i> 与同行对比</h4>
            <div class="comparison-chart">
                <div class="comparison-item">
                    <span>超越同行比例</span>
                    <div class="comparison-bar">
                        <div class="comparison-progress" style="width: ${competitiveness.overall}%"></div>
                    </div>
                    <span>${competitiveness.overall}%</span>
                </div>
            </div>
        </div>
    `;
}

/**
 * 生成目标岗位详情
 */
function generateTargetRoleDetail(data) {
    const targetRole = data.target_role || {
        position: '高级前端工程师',
        fit_score: 85,
        requirements_met: 8,
        total_requirements: 10,
        gaps: ['React Native经验', '微服务架构']
    };
    
    return `
        <div class="detail-section">
            <h4><i class="fas fa-briefcase"></i> 目标岗位信息</h4>
            <div class="detail-metrics-grid">
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${targetRole.fit_score}%</div>
                    <div class="detail-metric-label">适配度</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${targetRole.requirements_met}/${targetRole.total_requirements}</div>
                    <div class="detail-metric-label">需求满足</div>
                </div>
            </div>
        </div>
        
        <div class="detail-section">
            <h4><i class="fas fa-check-circle"></i> 已满足要求</h4>
            <p>您已经满足了该岗位的大部分核心要求，具备良好的竞争优势。</p>
        </div>
        
        <div class="detail-section">
            <h4><i class="fas fa-exclamation-circle"></i> 技能缺口</h4>
            <ul>
                ${(targetRole.gaps || []).map(gap => `<li>${gap}</li>`).join('')}
            </ul>
        </div>
    `;
}

/**
 * 生成推荐岗位详情
 */
function generateRecommendedPositionsDetail(data) {
    const positions = data.recommended_positions || [
        {
            title: '前端开发工程师',
            company: 'ABC科技',
            match: 92,
            salary: '15-25K',
            location: '北京',
            skills: ['React', 'JavaScript', 'CSS'],
            requirements: '3年以上前端开发经验',
            description: '负责前端开发，参与产品设计和优化',
            company_size: '500-1000人',
            company_type: '互联网公司',
            benefits: ['五险一金', '带薪年假', '弹性工作', '技能培训']
        },
        {
            title: '高级前端工程师',
            company: 'XYZ互联网',
            match: 88,
            salary: '20-30K',
            location: '上海',
            skills: ['Vue.js', 'TypeScript', 'Webpack'],
            requirements: '5年以上前端开发经验',
            description: '高级前端工程师，技术架构设计',
            company_size: '1000+人',
            company_type: '大型企业',
            benefits: ['丰厚年终奖', '医疗保险', '子女教育', '股票期权']
        },
        {
            title: 'React开发工程师',
            company: 'DEF创新',
            match: 85,
            salary: '18-28K',
            location: '深圳',
            skills: ['React', 'Node.js', 'MongoDB'],
            requirements: '2年以上React开发经验',
            description: 'React全栈开发，前后端技术维护',
            company_size: '50-200人',
            company_type: '创业公司',
            benefits: ['股权激励', '灵活办公', '技术大会', '健身补贴']
        }
    ];
    
    // 计算统计数据
    const avgMatchScore = positions.reduce((sum, pos) => sum + pos.match, 0) / positions.length;
    const topSkills = {};
    positions.forEach(pos => {
        (pos.skills || []).forEach(skill => {
            topSkills[skill] = (topSkills[skill] || 0) + 1;
        });
    });
    const mostRequiredSkills = Object.entries(topSkills)
        .sort(([,a], [,b]) => b - a)
        .slice(0, 5)
        .map(([skill]) => skill);
    
    return `
        <div class="modern-detail-container">
            <!-- 职位推荐总览 -->
            <div class="overview-panel">
                <div class="score-circle-container">
                    <div class="score-circle" data-score="${avgMatchScore.toFixed(0)}">
                        <div class="score-value">${avgMatchScore.toFixed(0)}</div>
                        <div class="score-label">平均匹配度</div>
                        </div>
                    <div class="skill-level-badge">智能推荐</div>
                        </div>
                <div class="quick-stats">
                    <div class="stat-item excellent">
                        <div class="stat-number">${positions.length}</div>
                        <div class="stat-label">推荐职位</div>
                    </div>
                    <div class="stat-item good">
                        <div class="stat-number">${positions.filter(p => p.match >= 80).length}</div>
                        <div class="stat-label">高匹配</div>
                    </div>
                    <div class="stat-item attention">
                        <div class="stat-number">${mostRequiredSkills.length}</div>
                        <div class="stat-label">核心技能</div>
                    </div>
                </div>
            </div>

            <!-- 职位详细列表 -->
            <div class="positions-showcase">
                <h4><i class="fas fa-star"></i> 精选职位推荐</h4>
                <div class="positions-list-modern">
                    ${positions.map((position, index) => {
                        const matchLevel = position.match >= 90 ? 'excellent' : 
                                         position.match >= 80 ? 'good' : 'attention';
                        const priorityText = index === 0 ? '首选推荐' : 
                                           index === 1 ? '优质选择' : '潜力机会';
                        
                        return `
                            <div class="position-card-modern ${matchLevel}">
                                <div class="position-ribbon">
                                    <span class="ribbon-text">${priorityText}</span>
                                </div>
                                
                                <div class="position-header-modern">
                                    <div class="position-title-section">
                                        <h5 class="position-title">${position.title}</h5>
                                        <div class="company-info">
                                            <span class="company-name">${position.company}</span>
                                            <span class="company-meta">${position.company_size} · ${position.company_type}</span>
                                        </div>
                                    </div>
                                    <div class="match-score-modern ${matchLevel}">
                                        <div class="score-number">${position.match}</div>
                                        <div class="score-text">匹配度</div>
                                    </div>
                                </div>
                                
                                <div class="position-highlights">
                                    <div class="highlight-item salary">
                                        <i class="fas fa-coins"></i>
                                        <div class="highlight-content">
                                            <span class="highlight-label">薪资范围</span>
                                            <span class="highlight-value">${position.salary}</span>
                                        </div>
                                    </div>
                                    <div class="highlight-item location">
                                        <i class="fas fa-map-marker-alt"></i>
                                        <div class="highlight-content">
                                            <span class="highlight-label">工作地点</span>
                                            <span class="highlight-value">${position.location}</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="position-description">
                                    <p>${position.description}</p>
                                    <div class="requirements-text">
                                        <strong>任职要求：</strong>${position.requirements}
                                    </div>
                                </div>
                                
                                <div class="skills-section">
                                    <h6><i class="fas fa-tools"></i> 技能要求</h6>
                                    <div class="skills-tags">
                                        ${(position.skills || []).map(skill => `
                                            <span class="skill-tag-modern ${mostRequiredSkills.includes(skill) ? 'hot' : 'normal'}">
                                                ${skill}
                                                ${mostRequiredSkills.includes(skill) ? '<i class="fas fa-fire"></i>' : ''}
                                            </span>
                                            `).join('')}
                                        </div>
                                    </div>
        
                                <div class="benefits-section">
                                    <h6><i class="fas fa-gift"></i> 福利待遇</h6>
                                    <div class="benefits-grid">
                                        ${(position.benefits || []).map(benefit => `
                                            <div class="benefit-item">
                                                <i class="fas fa-check-circle"></i>
                                                <span>${benefit}</span>
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            </div>
                        `;
                    }).join('')}
                </div>
            </div>

            <!-- 求职策略建议 -->
            <div class="job-advice">
                <h4><i class="fas fa-lightbulb"></i> 智能求职建议</h4>
                <div class="advice-cards">
                    <div class="advice-card preparation">
                        <div class="advice-header">
                            <i class="fas fa-clipboard-check"></i>
                            <h5>面试准备</h5>
                    </div>
                        <ul class="advice-list">
                            <li>重点准备 ${mostRequiredSkills.slice(0,3).join('、')} 技术问题</li>
                            <li>梳理项目经验，突出解决问题的能力</li>
                            <li>了解目标公司的技术栈和业务模式</li>
                        </ul>
                </div>
                
                    <div class="advice-card strategy">
                        <div class="advice-header">
                            <i class="fas fa-chess"></i>
                            <h5>投递策略</h5>
                                </div>
                        <ul class="advice-list">
                            <li>优先申请匹配度 90% 以上的职位</li>
                            <li>工作日上午投递简历效果更佳</li>
                            <li>保持每周 3-5 个精准投递</li>
                        </ul>
                                </div>
                            </div>
            </div>
        </div>
    `;
}

function generateSkillSuggestionsDetail(data) {
    const missing = Array.isArray(data?.missing_skills) ? data.missing_skills : [];
    const strengths = Array.isArray(data?.strength_areas) ? data.strength_areas : [];

    const phases = [
        { key: 'foundation', name: '基础巩固（第1-2周）', icon: 'fa-seedling' },
        { key: 'practice', name: '项目实践（第3-5周）', icon: 'fa-tools' },
        { key: 'advanced', name: '进阶突破（第6-8周）', icon: 'fa-rocket' }
    ];

    const learningResources = (skill) => `
        <ul>
            <li><i class=\"fas fa-book\"></i> 官方文档：${skill}</li>
            <li><i class=\"fas fa-video\"></i> 系统课程：${skill} 实战</li>
            <li><i class=\"fas fa-code\"></i> 小项目：实现 ${skill} 的典型用例</li>
        </ul>
    `;

    return `
        <div class=\"detail-section\">\n            <h4><i class=\"fas fa-lightbulb\"></i> 总览</h4>
            <div class=\"detail-metrics-grid\">\n                <div class=\"detail-metric-card\">\n                    <div class=\"detail-metric-value\">${missing.length}</div>\n                    <div class=\"detail-metric-label\">缺失技能数</div>\n                </div>\n                <div class=\"detail-metric-card\">\n                    <div class=\"detail-metric-value\">${strengths.length}</div>\n                    <div class=\"detail-metric-label\">优势领域数</div>\n                </div>\n            </div>\n        </div>

        ${strengths.length ? `
        <div class=\"detail-section\">\n            <h4><i class=\"fas fa-star\"></i> 优势领域</h4>
            <div class=\"detail-metrics-grid\">\n                ${strengths.map(s => `
                    <div class=\"detail-metric-card\">\n                        <div class=\"detail-metric-value\">${s}</div>\n                        <div class=\"detail-metric-label\">可作为项目亮点</div>\n                    </div>
                `).join('')}\n            </div>\n        </div>` : ''}

        ${missing.length ? `
        <div class=\"detail-section\">\n            <h4><i class=\"fas fa-exclamation-triangle\"></i> 建议补强技能</h4>
            <div class=\"detail-metrics-grid\">\n                ${missing.map(s => `
                    <div class=\"detail-metric-card\">\n                        <div class=\"detail-metric-value\">${s}</div>\n                        <div class=\"detail-metric-label\">优先级：高</div>\n                    </div>
                `).join('')}\n            </div>\n        </div>` : '<div class=\"detail-section\"><p>暂无缺失技能</p></div>'}

        <div class=\"detail-section\">\n            <h4><i class=\"fas fa-route\"></i> 8周学习路线</h4>
            <div class=\"timeline\">\n                ${phases.map(p => `
                    <div class=\"timeline-item\">\n                        <div class=\"timeline-marker\"></div>\n                        <div class=\"timeline-content\">\n                            <h5><i class=\"fas ${p.icon}\"></i> ${p.name}</h5>\n                            <p>围绕关键技能进行阶段性推进：
                            ${missing.slice(0, 3).map(ms => `【${ms}】`).join(' ')}。</p>\n                            ${missing.length ? learningResources(missing[0]) : ''}\n                        </div>\n                    </div>
                `).join('')}\n            </div>\n        </div>

        <div class=\"detail-section\">\n            <h4><i class=\"fas fa-chart-bar\"></i> 提升预估</h4>
            <div class=\"detail-metrics-grid\">\n                <div class=\"detail-metric-card\">\n                    <div class=\"detail-metric-value\">+10%~20%</div>\n                    <div class=\"detail-metric-label\">预计匹配度提升</div>\n                </div>\n                <div class=\"detail-metric-card\">\n                    <div class=\"detail-metric-value\">6-8周</div>\n                    <div class=\"detail-metric-label\">计划周期</div>\n                </div>\n            </div>\n        </div>
    `;
}


/**
 * 生成默认详情
 */
function generateDefaultDetail(analysisType, data) {
    return `
        <div class="detail-section">
            <h4><i class="fas fa-info-circle"></i> ${getAnalysisTypeTitle(analysisType)}</h4>
            <div class="detail-metrics-grid">
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${data.score || 0}%</div>
                    <div class="detail-metric-label">评分</div>
                </div>
                <div class="detail-metric-card">
                    <div class="detail-metric-value">${data.level || 'N/A'}</div>
                    <div class="detail-metric-label">等级</div>
                </div>
            </div>
            <div style="margin-top: 16px;">
                <p>${data.description || '暂无详细描述'}</p>
            </div>
        </div>
    `;
}

/**
 * 加载AI分析
 */
function loadAIAnalysis(analysisType, analysisData) {
    const container = document.getElementById('aiAnalysisContent');
    if (!container) return;
    
    // 显示加载状态
    container.innerHTML = `
        <div class="ai-analysis-loading">
            <i class="fas fa-brain fa-pulse"></i>
            <p>AI正在分析结果原因...</p>
        </div>
    `;
    
    // 模拟AI分析过程
    setTimeout(() => {
        container.innerHTML = generateAIAnalysis(analysisType, analysisData);
    }, 1500);
}

/**
 * 生成AI分析内容
 */
function generateAIAnalysis(analysisType, analysisData) {
    const analysis = getAIAnalysisContent(analysisType, analysisData);
    const intelligentAnalysis = generateIntelligentAnalysis(analysisType, analysisData);
    
    return `
        <div class="ai-analysis-reason">
            <div class="ai-analysis-header">
                <h5><i class="fas fa-brain"></i> AI智能分析</h5>
                <div class="ai-confidence">
                    <span class="confidence-label">可信度</span>
                    <div class="confidence-bar">
                        <div class="confidence-fill" style="width: ${intelligentAnalysis.confidence}%"></div>
                    </div>
                    <span class="confidence-value">${intelligentAnalysis.confidence}%</span>
                </div>
            </div>
            
            <div class="ai-summary">
                <i class="fas fa-lightbulb"></i>
                <p>${intelligentAnalysis.summary}</p>
            </div>
            
            <h5><i class="fas fa-search"></i> 深度解析</h5>
            <p class="analysis-explanation">${analysis.explanation}</p>
            
            <h5><i class="fas fa-chart-bar"></i> 关键影响因素</h5>
            <div class="factors-analysis">
                ${analysis.factors.map((factor, index) => `
                    <div class="factor-item">
                        <div class="factor-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="factor-content">
                            <span class="factor-text">${factor}</span>
                            <span class="factor-weight">权重: ${Math.max(85 - index * 8, 50)}%</span>
                        </div>
                    </div>
                                        `).join('')}
                                    </div>
            
            <h5><i class="fas fa-robot"></i> AI洞察</h5>
            <div class="ai-insights">
                ${intelligentAnalysis.insights.map(insight => `
                    <div class="insight-item">
                        <i class="fas fa-lightbulb"></i>
                        <span>${insight}</span>
                    </div>
                `).join('')}
                                </div>
                                
            <div class="ai-analysis-highlight">
                <i class="fas fa-thumbs-up"></i>
                <div class="highlight-content">
                    <strong>AI核心建议</strong>
                    <p>${analysis.suggestion}</p>
                </div>
            </div>
            
            <h5><i class="fas fa-tasks"></i> 个性化行动方案</h5>
            <div class="improvement-plan">
                ${analysis.improvements.map((improvement, index) => `
                    <div class="improvement-item">
                        <div class="step-number">${index + 1}</div>
                        <div class="improvement-content">
                            <span class="improvement-text">${improvement}</span>
                            <span class="priority ${getPriority(index)}">
                                ${getPriorityText(index)}
                            </span>
                        </div>
                    </div>
                `).join('')}
            </div>
            
            <div class="ai-analysis-footer">
                <div class="analysis-timestamp">
                    <i class="fas fa-clock"></i>
                    <span>分析时间: ${new Date().toLocaleString()}</span>
                </div>
                <div class="analysis-version">
                    <i class="fas fa-cog"></i>
                    <span>AI引擎 v2.1</span>
                </div>
            </div>
        </div>
    `;
}

/**
 * 获取AI分析内容
 */
function getAIAnalysisContent(analysisType, data) {
    const templates = {
        'skill_match': {
            explanation: '基于您的技能与目标岗位要求的对比分析，AI识别出了技能匹配程度和差距。',
            factors: [
                '编程语言熟练度与岗位要求的匹配程度',
                '框架和工具使用经验的相关性',
                '项目经验中技能应用的深度',
                '技能组合的完整性和互补性'
            ],
            suggestion: '重点提升核心技能，同时补充缺失的关键技术栈。',
            improvements: [
                '针对性学习缺失的核心技能',
                '通过实际项目强化现有技能',
                '关注新兴技术趋势',
                '建立技能学习计划'
            ]
        },
        'experience_gap': {
            explanation: '通过对比您的工作经验与岗位要求，AI分析了经验匹配度和潜在差距。',
            factors: [
                '工作年限与岗位要求的匹配度',
                '相关项目经验的质量和复杂度',
                '技术深度和广度的平衡',
                '团队协作和领导经验'
            ],
            suggestion: '通过高质量项目和持续学习弥补经验不足。',
            improvements: [
                '参与更复杂的技术项目',
                '主动承担技术难点',
                '提升项目管理能力',
                '积累行业相关经验'
            ]
        },
        'capability_radar': {
            explanation: '基于多维度能力评估，AI分析了您的技能雷达图，识别出强项和待提升领域。',
            factors: [
                '技术技能的深度和广度',
                '项目实践经验的丰富程度',
                '软技能和沟通协作能力',
                '学习能力和适应性'
            ],
            suggestion: '发挥优势技能，有针对性地提升薄弱环节。',
            improvements: [
                '强化核心技术能力',
                '提升跨团队协作技巧',
                '培养持续学习习惯',
                '增强问题解决能力'
            ]
        },
        'match_breakdown': {
            explanation: 'AI将整体匹配度分解为多个维度，帮助您理解各方面的匹配情况。',
            factors: [
                '技能与岗位要求的对应程度',
                '工作经验的相关性和深度',
                '教育背景的适配度',
                '地理位置和薪资期望的匹配'
            ],
            suggestion: '优先提升低分维度，均衡发展各项能力。',
            improvements: [
                '补强技能短板',
                '积累相关行业经验',
                '优化简历展示',
                '调整期望值设定'
            ]
        },
        'competitiveness': {
            explanation: 'AI通过市场数据和同行对比，评估了您在目标岗位上的竞争优势。',
            factors: [
                '技术能力在市场中的定位',
                '经验水平的相对优势',
                '教育背景的竞争力',
                '综合素质的市场认可度'
            ],
            suggestion: '保持技术优势，提升综合竞争力。',
            improvements: [
                '持续技术创新和学习',
                '建立个人技术品牌',
                '扩展专业网络',
                '参与开源项目贡献'
            ]
        },
        'target_role': {
            explanation: 'AI分析了您与目标岗位的适配程度，识别出优势和需要改进的地方。',
            factors: [
                '技能要求的满足程度',
                '经验背景的匹配度',
                '职业发展路径的一致性',
                '岗位责任的胜任能力'
            ],
            suggestion: '重点补齐关键技能缺口，提升岗位适配度。',
            improvements: [
                '学习目标岗位核心技能',
                '积累相关项目经验',
                '了解行业发展趋势',
                '准备面试和展示材料'
            ]
        },
        'recommended_positions': {
            explanation: 'AI基于您的背景和市场需求，推荐了最适合您的岗位机会。',
            factors: [
                '技能匹配度和发展潜力',
                '薪资水平和发展空间',
                '公司文化和工作环境',
                '职业发展前景'
            ],
            suggestion: '优先考虑高匹配度岗位，关注长期发展价值。',
            improvements: [
                '深入了解目标公司',
                '准备针对性的申请材料',
                '提升面试表现能力',
                '建立行业人脉关系'
            ]
        }
    };
    
    return templates[analysisType] || {
        explanation: 'AI正在分析您的情况，为您提供个性化的建议。',
        factors: ['数据完整性', '匹配算法准确性', '市场趋势分析'],
        suggestion: '建议关注核心竞争力的提升。',
        improvements: ['持续学习', '实践应用', '经验积累']
    };
}

/**
 * 重新生成AI分析
 */
function regenerateAIAnalysis() {
    if (!currentAnalysisDetail) return;
    
    const { type, data } = currentAnalysisDetail;
    loadAIAnalysis(type, data);
}

/**
 * 向AI提问
 */
function askAIQuestion() {
    // 这里可以集成聊天功能或打开问答对话框
    alert('AI问答功能即将上线，敬请期待！');
}

// 点击模态框外部关闭
document.addEventListener('click', function(e) {
    const modal = document.getElementById('analysisDetailModal');
    if (modal && e.target === modal) {
        closeAnalysisDetailModal();
    }
});

// ESC键关闭模态框
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeAnalysisDetailModal();
    }
});

/**
 * 生成智能分析内容
 */
function generateIntelligentAnalysis(analysisType, analysisData) {
    const analyses = {
        'skill_match': {
            confidence: 92,
            summary: '基于您的技能组合和目标岗位要求，AI检测到高度匹配的技术栈，特别是在前端开发领域表现出色。',
            insights: [
                '您的JavaScript和React技能在市场需求中排名前10%',
                '缺少的TypeScript技能是当前最值得投资的技术',
                '您的技能组合适合向全栈方向发展'
            ]
        },
        'capability_radar': {
            confidence: 88,
            summary: '能力雷达图显示您在技术实力和团队协作方面表现突出，学习能力强是您的核心竞争优势。',
            insights: [
                '技术能力与项目经验的结合度很高',
                '沟通协作能力超过70%的同行',
                '持续学习的习惯为职业发展提供强劲动力'
            ]
        },
        'match_breakdown': {
            confidence: 90,
            summary: '匹配度分解显示您在多个维度都有不错的表现，教育背景和工作地点是您的优势项。',
            insights: [
                '技能匹配度85%，在同级别候选人中排名前30%',
                '经验匹配需要提升，建议重点关注相关项目',
                '整体匹配度预期可提升至90%以上'
            ]
        },
        'competitiveness': {
            confidence: 85,
            summary: '您在目标岗位的竞争力处于中上水平，技术能力是主要优势，需要在经验积累上加强。',
            insights: [
                '技术能力排名前25%，有明显竞争优势',
                '工作经验相对薄弱，但成长潜力很大',
                '教育背景为竞争力增加了重要砝码'
            ]
        },
        'target_role': {
            confidence: 87,
            summary: '您与目标岗位的契合度良好，已满足80%的核心要求，剩余差距可通过短期学习快速弥补。',
            insights: [
                '核心技能要求满足度高，技术基础扎实',
                '项目经验需要更多复杂场景的历练',
                '软技能表现出色，符合团队协作要求'
            ]
        },
        'recommended_positions': {
            confidence: 93,
            summary: 'AI基于市场数据为您推荐的职位都具有很高的匹配度，建议优先关注成长型公司的机会。',
            insights: [
                '推荐岗位的平均匹配度达到88%',
                '薪资增长空间预期在20-35%之间',
                '多元化的选择有利于职业发展规划'
            ]
        }
    };
    
    return analyses[analysisType] || {
        confidence: 75,
        summary: 'AI正在深度分析您的数据，请稍后查看详细结果。',
        insights: ['分析正在进行中...']
    };
}

/**
 * 获取优先级样式
 */
function getPriority(index) {
    if (index === 0) return 'high';
    if (index === 1) return 'medium';
    return 'low';
}

/**
 * 获取优先级文本
 */
function getPriorityText(index) {
    if (index === 0) return '高优先级';
    if (index === 1) return '中优先级';
    return '低优先级';
}

// ==================== 美化辅助函数 ====================

/**
 * 获取能力对应的图标
 */
function getCapabilityIcon(capability) {
    const iconMap = {
        '技术能力': 'code',
        '项目经验': 'project-diagram',
        '团队协作': 'users',
        '学习能力': 'graduation-cap',
        '沟通表达': 'comments',
        '问题解决': 'puzzle-piece',
        '创新思维': 'lightbulb',
        '领导力': 'crown'
    };
    return iconMap[capability] || 'cog';
}

/**
 * 获取能力深度分析
 */
function getCapabilityInsight(capability, score) {
    if (capability.includes('技术')) {
        return score >= 80 ? '技术功底深厚，具备解决复杂问题的能力' : 
               score >= 60 ? '技术基础良好，需在深度和广度上继续提升' : 
               '建议加强核心技术栈学习，多做实践项目';
    } else if (capability.includes('项目')) {
        return score >= 80 ? '项目经验丰富，能独立承担复杂项目' : 
               score >= 60 ? '有一定项目经验，需参与更多挑战性项目' : 
               '建议积极参与项目，积累实战经验';
    } else if (capability.includes('团队')) {
        return score >= 80 ? '团队协作能力强，是团队中的核心成员' : 
               score >= 60 ? '具备基本协作能力，需提升沟通技巧' : 
               '建议多参与团队活动，提升协作意识';
    } else if (capability.includes('学习')) {
        return score >= 80 ? '学习能力突出，能快速掌握新技术' : 
               score >= 60 ? '学习态度积极，需提高学习效率' : 
               '建议制定学习计划，培养持续学习习惯';
    } else if (capability.includes('沟通')) {
        return score >= 80 ? '沟通表达能力强，能清晰传达技术方案' : 
               score >= 60 ? '基本沟通无障碍，需提升技术表达' : 
               '建议多练习技术分享，提升表达能力';
    }
    return score >= 80 ? '该能力表现优秀，可作为核心竞争力' : 
           score >= 60 ? '该能力有一定基础，还有提升空间' : 
           '该能力需要重点关注和提升';
}

/**
 * 获取能力提升建议
 */
function getCapabilityAction(capability, score) {
    if (capability.includes('技术')) {
        return score >= 80 ? '继续保持技术前沿性，关注新兴技术' : 
               score >= 60 ? '深入学习核心技术，参与开源项目' : 
               '制定系统学习计划，从基础开始扎实推进';
    } else if (capability.includes('项目')) {
        return score >= 80 ? '挑战更大规模的项目，担任技术负责人' : 
               score >= 60 ? '主动承担项目关键模块，提升影响力' : 
               '参与完整项目周期，积累端到端经验';
    }
    return score >= 80 ? '发挥优势，指导他人提升该能力' : 
           score >= 60 ? '制定提升计划，寻求实践机会' : 
           '重点关注，制定针对性学习方案';
}

/**
 * 生成发展路径
 */
function generateDevelopmentTracks(capabilities) {
    const entries = Object.entries(capabilities);
    const strongAreas = entries.filter(([_, score]) => score >= 80);
    const weakAreas = entries.filter(([_, score]) => score < 60);
    
    const tracks = [];
    
    if (strongAreas.length >= 2) {
        tracks.push({
            name: '专家发展路径',
            icon: 'crown',
            color: 'gold',
            description: '基于您的优势能力，向技术专家方向发展',
            steps: [
                '深化技术专业度，成为领域专家',
                '输出技术内容，建立个人品牌',
                '指导团队成员，提升影响力',
                '参与技术决策，推动创新项目'
            ]
        });
    }
    
    if (weakAreas.length > 0) {
        tracks.push({
            name: '平衡提升路径',
            icon: 'balance-scale',
            color: 'blue',
            description: '重点提升薄弱环节，实现全面发展',
            steps: [
                `优先提升${weakAreas[0][0]}等关键能力`,
                '寻找实践机会，在工作中应用新技能',
                '定期评估进展，调整学习策略',
                '达到均衡发展，提升综合竞争力'
            ]
        });
    }
    
    tracks.push({
        name: '创新探索路径',
        icon: 'rocket',
        color: 'purple',
        description: '探索新兴技术和方法，打造差异化优势',
        steps: [
            '关注行业趋势，学习前沿技术',
            '参与创新项目，积累新经验',
            '跨界学习，拓展知识边界',
            '建立创新思维，成为变革推动者'
        ]
    });
    
    return tracks.map(track => `
        <div class="development-track ${track.color}">
            <div class="track-header">
                <div class="track-icon">
                    <i class="fas fa-${track.icon}"></i>
                </div>
                <div class="track-info">
                    <h5>${track.name}</h5>
                    <p>${track.description}</p>
                </div>
            </div>
            <div class="track-steps">
                ${track.steps.map((step, index) => `
                    <div class="track-step">
                        <div class="step-number">${index + 1}</div>
                        <div class="step-content">${step}</div>
                    </div>
                `).join('')}
            </div>
        </div>
    `).join('');
}
/**
 * 生成90天提升计划
 */
function generate90DayPlan(capabilities) {
    const entries = Object.entries(capabilities);
    const improvementAreas = entries.filter(([_, score]) => score < 80).slice(0, 3);
    
    const phases = [
        { name: '第一阶段 (1-30天)', color: 'green', focus: '基础建设' },
        { name: '第二阶段 (31-60天)', color: 'blue', focus: '实践应用' },
        { name: '第三阶段 (61-90天)', color: 'purple', focus: '能力巩固' }
    ];
    
    return phases.map((phase, phaseIndex) => `
        <div class="plan-phase ${phase.color}">
            <div class="phase-header">
                <div class="phase-icon">${phaseIndex + 1}</div>
                <div class="phase-info">
                    <h5>${phase.name}</h5>
                    <span class="phase-focus">${phase.focus}</span>
                </div>
            </div>
            <div class="phase-tasks">
                ${improvementAreas.map(([capability, score]) => {
                    const tasks = {
                        0: [ // 第一阶段
                            `评估${capability}现状，制定学习计划`,
                            '搜集学习资源，建立知识体系',
                            '每日练习，建立学习习惯'
                        ],
                        1: [ // 第二阶段
                            `在项目中应用${capability}`,
                            '寻求反馈，持续改进',
                            '与他人交流，分享学习心得'
                        ],
                        2: [ // 第三阶段
                            `总结${capability}提升成果`,
                            '制定下一阶段目标',
                            '帮助他人，巩固所学知识'
                        ]
                    };
                    return `
                        <div class="phase-task">
                            <div class="task-capability">${capability}</div>
                            <div class="task-list">
                                ${tasks[phaseIndex]?.map(task => `
                                    <div class="task-item">
                                        <i class="fas fa-check-circle"></i>
                                        <span>${task}</span>
                                    </div>
                                `).join('') || ''}
                            </div>
                        </div>
                    `;
                }).join('')}
            </div>
        </div>
    `).join('');
}

/**
 * 获取平衡度分析
 */
function getBalanceAnalysis(entries) {
    const scores = entries.map(([_, score]) => score);
    const avg = scores.reduce((a, b) => a + b, 0) / scores.length;
    const variance = scores.reduce((acc, score) => acc + Math.pow(score - avg, 2), 0) / scores.length;
    const stdDev = Math.sqrt(variance);
    
    if (stdDev < 5) return '非常均衡';
    if (stdDev < 10) return '比较均衡';
    if (stdDev < 15) return '存在差异';
    return '发展不均衡';
}

/**
 * 获取职业方向建议
 */
function getCareerDirection(capabilities) {
    const techScore = capabilities['技术能力'] || 0;
    const teamScore = capabilities['团队协作'] || 0;
    const communicationScore = capabilities['沟通表达'] || 0;
    const projectScore = capabilities['项目经验'] || 0;
    
    if (techScore >= 85 && projectScore >= 80) return '技术专家';
    if (teamScore >= 85 && communicationScore >= 80) return '技术管理';
    if (techScore >= 80 && communicationScore >= 75) return '技术顾问';
    return '全栈发展';
}

/**
 * 计算职业发展潜力
 */
function calculateCareerPotential(capabilities) {
    const scores = Object.values(capabilities);
    const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length;
    
    // 技术能力权重
    const techWeight = (capabilities['技术深度'] || 0) * 0.25 + (capabilities['技术广度'] || 0) * 0.15;
    // 软技能权重
    const softWeight = (capabilities['沟通协作'] || 0) * 0.15 + (capabilities['学习能力'] || 0) * 0.15;
    // 经验和问题解决权重
    const expWeight = (capabilities['项目经验'] || 0) * 0.15 + (capabilities['问题解决'] || 0) * 0.15;
    
    const weightedScore = techWeight + softWeight + expWeight;
    
    let level, color, description;
    if (weightedScore >= 85) {
        level = '行业顶尖';
        color = 'linear-gradient(90deg, #10b981, #059669)';
        description = '您的综合能力已达到行业顶尖水平，具备成为技术专家或团队领导者的潜质。建议专注于战略思维和行业影响力的提升。';
    } else if (weightedScore >= 75) {
        level = '资深水平';
        color = 'linear-gradient(90deg, #3b82f6, #1d4ed8)';
        description = '您已达到资深专业人士水平，在多个维度表现优秀。建议继续深化专业技能，并向架构师或管理岗位发展。';
    } else if (weightedScore >= 65) {
        level = '中高级';
        color = 'linear-gradient(90deg, #8b5cf6, #7c3aed)';
        description = '您处于中高级专业水平，具备扎实的基础能力。建议重点提升技术深度或拓展业务理解，为晋升做准备。';
    } else if (weightedScore >= 50) {
        level = '中级水平';
        color = 'linear-gradient(90deg, #f59e0b, #d97706)';
        description = '您已具备中级专业能力，在某些领域表现良好。建议制定系统的提升计划，重点强化核心技能。';
    } else {
        level = '初中级';
        color = 'linear-gradient(90deg, #ef4444, #dc2626)';
        description = '您正处于技能发展的关键阶段，建议专注基础能力建设，多参与实践项目来积累经验。';
    }
    
    return {
        score: Math.round(weightedScore),
        level,
        color,
        description
    };
}

/**
 * 生成能力洞察
 */
function generateCapabilityInsight(capabilities, avgScore, balance) {
    const topCapability = Object.entries(capabilities).reduce((a, b) => a[1] > b[1] ? a : b);
    const weakestCapability = Object.entries(capabilities).reduce((a, b) => a[1] < b[1] ? a : b);
    
    let personalityType = '';
    const techDepth = capabilities['技术深度'] || 0;
    const techBreadth = capabilities['技术广度'] || 0;
    const communication = capabilities['沟通协作'] || 0;
    const innovation = capabilities['创新思维'] || 0;
    
    if (techDepth > 80 && techBreadth > 75) {
        personalityType = '全栈技术专家型';
    } else if (techDepth > 85) {
        personalityType = '深度技术专家型';
    } else if (communication > 85 && techDepth > 70) {
        personalityType = '技术管理型';
    } else if (innovation > 80 && techBreadth > 75) {
        personalityType = '创新驱动型';
    } else if (balance > 75) {
        personalityType = '均衡发展型';
    } else {
        personalityType = '潜力成长型';
    }
    
    return `您展现出${personalityType}的职业特质，最突出的能力是${topCapability[0]}(${Math.round(topCapability[1])}分)。
            ${balance > 70 ? '各项能力发展较为均衡，适合承担综合性强的工作。' : 
              `建议重点提升${weakestCapability[0]}，以实现更全面的发展。`}
            您的综合评分为${Math.round(avgScore)}分，${avgScore >= 75 ? '已具备较强的市场竞争力' : '还有较大的成长空间'}。`;
}

/**
 * 生成发展建议计划
 */
function generateDevelopmentPlan(capabilities, data) {
    const sortedCaps = Object.entries(capabilities).sort((a, b) => a[1] - b[1]);
    const improvementAreas = sortedCaps.slice(0, 3); // 取最需要提升的3项
    
    const plans = improvementAreas.map(([skill, score]) => {
        let timeframe, methods, expectedGain;
        
        if (score < 50) {
            timeframe = '3-6个月';
            expectedGain = 15;
            methods = generateIntensivePlan(skill);
        } else if (score < 70) {
            timeframe = '2-4个月';
            expectedGain = 12;
            methods = generateModeratePlan(skill);
        } else {
            timeframe = '1-3个月';
            expectedGain = 8;
            methods = generateAdvancedPlan(skill);
        }
        
        return {
            skill,
            currentScore: score,
            targetScore: Math.min(100, score + expectedGain),
            timeframe,
            methods,
            priority: score < 50 ? '高' : score < 70 ? '中' : '低'
        };
    });
    
    return `
        <div class="detail-section development-plan-section">
            <h4><i class="fas fa-rocket"></i> 个性化发展规划</h4>
            <div class="development-roadmap">
                ${plans.map((plan, index) => `
                    <div class="development-milestone">
                        <div class="milestone-header">
                            <div class="milestone-number">${index + 1}</div>
                            <div class="milestone-info">
                                <h5>${plan.skill}提升计划</h5>
                                <div class="milestone-meta">
                                    <span class="priority priority-${plan.priority === '高' ? 'high' : plan.priority === '中' ? 'medium' : 'low'}">
                                        优先级: ${plan.priority}
                                    </span>
                                    <span class="timeframe">预计周期: ${plan.timeframe}</span>
                                </div>
                            </div>
                            <div class="score-improvement">
                                <span class="current-score">${Math.round(plan.currentScore)}</span>
                                <i class="fas fa-arrow-right"></i>
                                <span class="target-score">${Math.round(plan.targetScore)}</span>
                            </div>
                        </div>
                        <div class="improvement-methods">
                            ${plan.methods.map(method => `
                                <div class="method-item">
                                    <i class="fas fa-check-circle"></i>
                                    <span>${method}</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `).join('')}
            </div>
            
            <div class="development-summary">
                <div class="summary-card">
                    <h5><i class="fas fa-target"></i> 发展目标</h5>
                    <p>通过系统性提升，预计在${plans[0].timeframe}内实现综合能力显著提升，
                    重点突破${plans[0].skill}短板，整体竞争力提升15-25%。</p>
                </div>
                <div class="summary-card">
                    <h5><i class="fas fa-calendar-alt"></i> 阶段规划</h5>
                    <ul class="phase-list">
                        <li><strong>第一阶段：</strong>重点突破${plans[0].skill}，建立基础优势</li>
                        <li><strong>第二阶段：</strong>同步提升${plans[1].skill}，增强综合实力</li>
                        <li><strong>第三阶段：</strong>完善${plans[2].skill}，实现全面发展</li>
                    </ul>
                </div>
            </div>
        </div>
    `;
}

/**
 * 生成不同强度的提升计划
 */
function generateIntensivePlan(skill) {
    const plans = {
        '技术深度': [
            '制定核心技术栈深度学习路线图',
            '每周至少15小时专项技术训练',
            '参与开源项目贡献代码',
            '寻找技术导师进行一对一指导',
            '完成3-5个高难度技术挑战项目'
        ],
        '技术广度': [
            '每月学习2-3个新技术框架',
            '建立技术知识图谱和学习笔记',
            '参加技术会议和工作坊',
            '关注行业技术趋势和最佳实践',
            '跨领域技术实践项目'
        ],
        '沟通协作': [
            '参加演讲俱乐部或技术分享活动',
            '练习技术文档写作和代码注释',
            '主动参与团队讨论和决策',
            '学习项目管理和团队协作工具',
            '寻求跨部门合作机会'
        ],
        '学习能力': [
            '建立系统化学习方法和习惯',
            '使用费曼学习法深度理解概念',
            '定期总结和复盘学习成果',
            '建立知识管理系统',
            '培养主动学习和自我驱动能力'
        ]
    };
    return plans[skill] || plans['学习能力'];
}

function generateModeratePlan(skill) {
    const plans = {
        '技术深度': [
            '深入研究当前技术栈的高级特性',
            '参与代码审查和技术讨论',
            '完成2-3个中等复杂度项目',
            '阅读技术书籍和官方文档'
        ],
        '技术广度': [
            '每月接触1-2个新技术',
            '参与技术社区和论坛讨论',
            '关注技术博客和资讯',
            '尝试不同的开发工具和方法'
        ],
        '沟通协作': [
            '积极参与团队会议发言',
            '协助新人培训和知识分享',
            '改善文档和注释质量',
            '学习有效沟通技巧'
        ]
    };
    return plans[skill] || ['制定针对性学习计划', '寻求实践机会', '定期评估进展', '调整学习策略'];
}

function generateAdvancedPlan(skill) {
    const plans = {
        '技术深度': [
            '研究前沿技术和架构模式',
            '承担技术难点攻关任务',
            '指导初级开发者'
        ],
        '技术广度': [
            '探索新兴技术领域',
            '建立技术选型和评估能力',
            '参与技术决策制定'
        ],
        '沟通协作': [
            '提升技术影响力',
            '参与或组织技术分享',
            '建立良好的合作关系网络'
        ]
    };
    return plans[skill] || ['继续保持并精进现有优势', '拓展影响力和认知边界', '承担更多挑战性任务'];
}

/**
 * 新增辅助函数：获取评分等级
 */
function getScoreLevel(score) {
    if (score >= 90) return '卓越水平 ⭐⭐⭐⭐⭐';
    if (score >= 80) return '优秀水平 ⭐⭐⭐⭐';
    if (score >= 70) return '良好水平 ⭐⭐⭐';
    if (score >= 60) return '合格水平 ⭐⭐';
    return '待提升 ⭐';
}

function getBalanceLevel(balance) {
    if (balance >= 80) return '高度均衡';
    if (balance >= 70) return '相对均衡';
    if (balance >= 60) return '略有差距';
    return '发展不均';
}

function getStrengthLevel(count) {
    if (count >= 5) return '优势突出';
    if (count >= 3) return '有所专长';
    if (count >= 1) return '初显优势';
    return '潜力待挖';
}

function getPotentialLevel(potential) {
    if (potential >= 90) return '潜力巨大';
    if (potential >= 80) return '发展稳健';
    if (potential >= 70) return '前景良好';
    return '需要突破';
}

function getScoreColor(score) {
    if (score >= 80) return 'linear-gradient(135deg, #10b981, #059669)';
    if (score >= 70) return 'linear-gradient(135deg, #3b82f6, #1d4ed8)';
    if (score >= 60) return 'linear-gradient(135deg, #f59e0b, #d97706)';
    return 'linear-gradient(135deg, #ef4444, #dc2626)';
}

/**
 * 获取职业人格类型
 */
function getPersonalityType(capabilities) {
    const techAvg = (capabilities['技术深度'] + capabilities['技术广度']) / 2;
    const softAvg = (capabilities['沟通协作'] + capabilities['学习能力']) / 2;
    const creativity = capabilities['创新思维'] || 0;
    const experience = capabilities['项目经验'] || 0;
    
    if (techAvg >= 85 && softAvg >= 80) return '全能型技术专家';
    if (techAvg >= 90) return '深度技术专家';
    if (softAvg >= 85 && techAvg >= 70) return '技术管理者';
    if (creativity >= 80 && techAvg >= 75) return '创新驱动者';
    if (experience >= 85) return '项目专家';
    if (softAvg >= 80) return '团队协作者';
    return '潜力成长者';
}

/**
 * 生成增强版职业画像洞察
 */
function generateEnhancedPersonalityInsight(capabilities, personalityType) {
    const insights = {
        '全能型技术专家': '您具备罕见的技术与管理双重天赋，既能深入技术细节，又能统筹全局。适合担任架构师、技术总监等高阶职位。',
        '深度技术专家': '您的技术能力极为突出，在专业领域有深厚造诣。建议继续深耕技术栈，成为行业技术权威和意见领袖。',
        '技术管理者': '您在技术理解和人员管理方面都表现优异，具备成为优秀技术 Leader 的潜质。建议向 CTO 路线发展。',
        '创新驱动者': '您具有敏锐的技术嗅觉和创新思维，能够洞察技术趋势。适合在初创公司或技术前沿领域发挥价值。',
        '项目专家': '您的项目管理和执行能力突出，能确保复杂项目顺利交付。建议向项目总监、产品负责人方向发展。',
        '团队协作者': '您具备出色的软技能，是团队中的黏合剂。建议在保持技术能力的同时，发展更多管理技能。',
        '潜力成长者': '您正处于快速成长期，各项能力均衡发展。建议制定清晰的职业规划，重点突破1-2个核心能力。'
    };
    return insights[personalityType] || '您展现出独特的能力组合，建议根据个人兴趣选择发展方向。';
}

/**
 * 获取职业画像标签
 */
function getPersonalityTags(capabilities, personalityType) {
    const baseTags = [];
    
    if (capabilities['技术深度'] >= 80) baseTags.push('技术精英');
    if (capabilities['技术广度'] >= 80) baseTags.push('全栈能手');
    if (capabilities['沟通协作'] >= 80) baseTags.push('团队核心');
    if (capabilities['创新思维'] >= 80) baseTags.push('创新先锋');
    if (capabilities['学习能力'] >= 80) baseTags.push('学习达人');
    if (capabilities['项目经验'] >= 80) baseTags.push('项目老手');
    if (capabilities['问题解决'] >= 80) baseTags.push('解决专家');
    if (capabilities['市场价值'] >= 80) baseTags.push('市场香饽饽');
    
    return baseTags.length > 0 ? baseTags : ['有潜力', '在成长'];
}

/**
 * 获取市场定位信息
 */
function getMarketPosition(avgScore, capabilities) {
    const techScore = (capabilities['技术深度'] + capabilities['技术广度']) / 2;
    const experienceScore = capabilities['项目经验'] || 0;
    
    if (avgScore >= 85 && techScore >= 85) {
        return {
            category: '高级专家',
            description: '您在市场上属于稀缺的高级技术人才，具备很强的议价能力和选择权。',
            salaryRange: '30K-60K',
            suitableRoles: ['技术专家', '架构师', '技术总监']
        };
    } else if (avgScore >= 75 && experienceScore >= 75) {
        return {
            category: '资深工程师',
            description: '您已达到资深工程师水平，在团队中能够独当一面，有良好的发展前景。',
            salaryRange: '20K-35K',
            suitableRoles: ['高级工程师', '技术负责人', 'Team Lead']
        };
    } else if (avgScore >= 65) {
        return {
            category: '中级工程师',
            description: '您具备扎实的技术基础，正处于向高级工程师进阶的关键期。',
            salaryRange: '15K-25K',
            suitableRoles: ['中级工程师', '全栈工程师', '项目开发者']
        };
    } else {
        return {
            category: '初中级工程师',
            description: '您正在技术成长的道路上稳步前进，建议专注基础能力建设。',
            salaryRange: '8K-18K',
            suitableRoles: ['初级工程师', '开发工程师', '实习生']
        };
    }
}

// 智能匹配功能的剩余函数
async function callNaturalLanguageSearchAPI(searchText) {
    try {
        // 先尝试从JH系统获取真实职位数据
        const filters = getAdvancedFilters();
        const response = await fetch(`/api/jh/jobs?${buildQueryParams(searchText, filters)}`);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        // 将JH系统的职位数据转换为智能匹配格式
        const convertedJobs = convertJHJobsToMatchFormat(data.jobs || data.data || [], searchText);
        
        // 如果没有找到职位，尝试其他API
        if (convertedJobs.length === 0) {
            return await tryAlternativeAPIs(searchText, filters);
        }
        
        return convertedJobs;
        
    } catch (error) {
        console.error('API调用失败:', error);
        // 尝试备用API
        return await tryAlternativeAPIs(searchText, getAdvancedFilters());
    }
}

function buildQueryParams(searchText, filters) {
    const params = new URLSearchParams();
    
    if (searchText) {
        params.append('search_query', searchText);
    }
    if (filters.salary_min) {
        params.append('salary_min', filters.salary_min);
    }
    if (filters.salary_max) {
        params.append('salary_max', filters.salary_max);
    }
    if (filters.locations && filters.locations.length > 0) {
        params.append('location', filters.locations[0]);
    }
    if (filters.work_modes && filters.work_modes.includes('remote')) {
        params.append('work_from_home', 'true');
    }
    
    params.append('page_size', '20');
    params.append('page', '1');
    
    return params.toString();
}

async function tryAlternativeAPIs(searchText, filters) {
    try {
        // 尝试demo候选人API
        const demoResponse = await fetch(`/api/demo/candidate/jobs/search?q=${encodeURIComponent(searchText)}&limit=20`);
        if (demoResponse.ok) {
            const demoData = await demoResponse.json();
            if (demoData.status === 'success' && demoData.data) {
                return convertDemoJobsToMatchFormat(demoData.data, searchText);
            }
        }
        
        // 尝试HR demo API
        const hrResponse = await fetch(`/api/demo/hr/jobs?limit=20`);
        if (hrResponse.ok) {
            const hrData = await hrResponse.json();
            if (hrData.status === 'success' && hrData.data) {
                return convertDemoJobsToMatchFormat(hrData.data, searchText);
            }
        }
        
        // 最后使用模拟数据
        return generateMockSearchResults(searchText);
        
    } catch (error) {
        console.error('备用API也失败了:', error);
        return generateMockSearchResults(searchText);
    }
}

function convertJHJobsToMatchFormat(jobs, searchText) {
    return jobs.map((job, index) => {
        // 计算匹配分数
        const matchScores = calculateJobMatchScores(job, searchText);
        
        return {
            job_id: job.id?.toString() || `jh_${index}`,
            job_title: job.job_title || job.job_title_short || '未知职位',
            company: job.company_name || '未知公司',
            location: job.job_location || job.search_location || '未知地点',
            salary: formatSalary(job.salary_year_avg, job.salary_rate),
            skills: parseSkills(job.job_skills || job.job_type_skills),
            match_score: matchScores.overall,
            skill_match: matchScores.skill,
            salary_match: matchScores.salary,
            location_match: matchScores.location,
            culture_match: matchScores.culture,
            growth_match: matchScores.growth,
            stability_match: matchScores.stability,
            description: `通过 ${job.job_via || '招聘网站'} 发布的职位`,
            benefits: getBenefitsFromJob(job),
            work_mode: job.job_work_from_home ? 'remote' : 'onsite',
            company_size: 'medium', // JH数据中没有公司规模信息
            match_explanation: generateMatchExplanation(job, searchText, matchScores),
            missing_skills: generateMissingSkills(job, searchText),
            growth_suggestions: generateGrowthSuggestions(job, searchText)
        };
    });
}

function convertDemoJobsToMatchFormat(jobs, searchText) {
    return jobs.map((job, index) => {
        const matchScores = calculateJobMatchScores(job, searchText);
        
        return {
            job_id: job.id?.toString() || `demo_${index}`,
            job_title: job.title || job.position || job.job_title || '未知职位',
            company: job.company || job.company_name || '未知公司',
            location: job.location || job.city || '未知地点',
            salary: job.salary || job.salary_range || '面议',
            skills: Array.isArray(job.skills) ? job.skills : 
                   (job.requirements ? job.requirements.slice(0, 4) : ['相关技能']),
            match_score: matchScores.overall,
            skill_match: matchScores.skill,
            salary_match: matchScores.salary,
            location_match: matchScores.location,
            culture_match: matchScores.culture,
            growth_match: matchScores.growth,
            stability_match: matchScores.stability,
            description: job.description || job.job_description || '职位描述暂无',
            benefits: job.benefits || ['五险一金', '带薪年假'],
            work_mode: job.remote || job.work_from_home ? 'remote' : 
                      job.hybrid ? 'hybrid' : 'onsite',
            company_size: job.company_size || 'medium',
            match_explanation: generateMatchExplanation(job, searchText, matchScores),
            missing_skills: generateMissingSkills(job, searchText),
            growth_suggestions: generateGrowthSuggestions(job, searchText)
        };
    });
}

function calculateJobMatchScores(job, searchText) {
    // 基于搜索文本和职位信息计算各维度匹配分数
    const searchLower = searchText.toLowerCase();
    const jobTitle = (job.job_title || job.title || '').toLowerCase();
    const jobDesc = (job.description || job.job_description || '').toLowerCase();
    const jobSkills = (job.job_skills || job.skills || []).join(' ').toLowerCase();
    
    // 技能匹配分数
    let skillMatch = 0.6; // 基础分数
    if (jobTitle.includes('python') || jobSkills.includes('python')) skillMatch += 0.1;
    if (jobTitle.includes('javascript') || jobSkills.includes('javascript')) skillMatch += 0.1;
    if (jobTitle.includes('react') || jobSkills.includes('react')) skillMatch += 0.1;
    if (searchLower.includes('senior') && jobTitle.includes('senior')) skillMatch += 0.1;
    
    // 薪资匹配分数
    const salaryMatch = 0.7 + Math.random() * 0.25; // 0.7-0.95
    
    // 地理位置匹配分数
    const locationMatch = 0.65 + Math.random() * 0.3; // 0.65-0.95
    
    // 文化契合分数
    const cultureMatch = 0.6 + Math.random() * 0.35; // 0.6-0.95
    
    // 成长潜力分数
    const growthMatch = 0.65 + Math.random() * 0.3; // 0.65-0.95
    
    // 稳定性分数
    const stabilityMatch = 0.55 + Math.random() * 0.35; // 0.55-0.9
    
    // 计算加权总分
    const overall = (
        skillMatch * matchingWeights.skill +
        salaryMatch * matchingWeights.salary +
        locationMatch * matchingWeights.location +
        cultureMatch * matchingWeights.culture +
        growthMatch * matchingWeights.growth +
        stabilityMatch * matchingWeights.stability
    ) / Object.values(matchingWeights).reduce((sum, w) => sum + w, 0);
    
    return {
        overall: Math.min(0.95, overall),
        skill: Math.min(0.98, skillMatch),
        salary: salaryMatch,
        location: locationMatch,
        culture: cultureMatch,
        growth: growthMatch,
        stability: stabilityMatch
    };
}

function formatSalary(yearAvg, rate) {
    if (yearAvg && yearAvg > 0) {
        if (yearAvg > 100000) {
            return `${Math.round(yearAvg / 10000)}万`;
        } else if (yearAvg > 10000) {
            return `${Math.round(yearAvg / 1000)}K`;
        } else {
            return `${Math.round(yearAvg)}元`;
        }
    }
    if (rate) {
        return rate;
    }
    return '面议';
}

function parseSkills(skillsStr) {
    if (Array.isArray(skillsStr)) {
        return skillsStr.slice(0, 6);
    }
    if (typeof skillsStr === 'string') {
        return skillsStr.split(/[,，;；\s]+/)
            .map(s => s.trim())
            .filter(s => s.length > 0)
            .slice(0, 6);
    }
    return ['相关技能'];
}

function getBenefitsFromJob(job) {
    const benefits = [];
    if (job.job_health_insurance) benefits.push('医疗保险');
    if (job.job_work_from_home) benefits.push('远程工作');
    if (!job.job_no_degree_mention) benefits.push('学历要求');
    
    // 添加一些默认福利
    if (benefits.length === 0) {
        benefits.push('五险一金', '带薪年假');
    }
    
    return benefits;
}

function generateMatchExplanation(job, searchText, matchScores) {
    const explanations = [];
    
    if (matchScores.skill > 0.8) {
        explanations.push('技能匹配度很高');
    }
    if (matchScores.salary > 0.8) {
        explanations.push('薪资符合期望');
    }
    if (matchScores.growth > 0.8) {
        explanations.push('成长空间较大');
    }
    
    if (explanations.length === 0) {
        explanations.push('基本符合您的求职要求');
    }
    
    return explanations.join('，') + '。';
}

function generateMissingSkills(job, searchText) {
    const commonMissingSkills = [
        'Docker', 'Kubernetes', 'AWS', 'TypeScript', 
        'Microservices', 'GraphQL', 'Redis', 'MongoDB'
    ];
    
    // 随机选择2-3个缺失技能
    const count = Math.floor(Math.random() * 2) + 2;
    const shuffled = [...commonMissingSkills].sort(() => 0.5 - Math.random());
    return shuffled.slice(0, count);
}

function generateGrowthSuggestions(job, searchText) {
    const suggestions = [
        '学习云计算技术', '掌握容器化部署', '了解微服务架构',
        '提升数据库优化能力', '学习前端框架', '掌握DevOps工具',
        '提升系统设计能力', '学习机器学习基础'
    ];
    
    const count = Math.floor(Math.random() * 2) + 2;
    const shuffled = [...suggestions].sort(() => 0.5 - Math.random());
    return shuffled.slice(0, count);
}

function getAdvancedFilters() {
    return {
        salary_min: document.getElementById('salaryMin')?.value || null,
        salary_max: document.getElementById('salaryMax')?.value || null,
        locations: Array.from(document.getElementById('locationFilter')?.selectedOptions || []).map(o => o.value),
        work_modes: Array.from(document.querySelectorAll('input[type="checkbox"]:checked')).map(cb => cb.value),
        company_size: document.getElementById('companySizeFilter')?.value || null,
        tech_stack: document.getElementById('techStackFilter')?.value?.split(',').map(s => s.trim()).filter(s => s) || [],
        benefits: Array.from(document.querySelectorAll('.checkbox-group input[type="checkbox"]:checked')).map(cb => cb.value)
    };
}

function generateMockSearchResults(searchText) {
    // 模拟搜索结果
    const mockJobs = [
        {
            job_id: '1',
            job_title: 'Senior Python Developer',
            company: 'TechCorp AI',
            location: '北京',
            salary: '25-35万',
            skills: ['Python', 'Django', 'MySQL', 'Redis'],
            match_score: 0.92,
            skill_match: 0.95,
            salary_match: 0.88,
            location_match: 0.95,
            culture_match: 0.89,
            growth_match: 0.91,
            stability_match: 0.85,
            description: '负责后端系统开发，参与架构设计',
            benefits: ['五险一金', '弹性工作', '期权'],
            work_mode: 'hybrid',
            company_size: 'medium',
            match_explanation: '您的Python技能与岗位要求高度匹配，薪资符合期望范围',
            missing_skills: ['Kubernetes', 'Microservices'],
            growth_suggestions: ['学习容器化技术', '了解微服务架构']
        },
        {
            job_id: '2',
            job_title: 'Data Scientist',
            company: 'AI Innovation Lab',
            location: '上海',
            salary: '20-30万',
            skills: ['Python', 'Machine Learning', 'TensorFlow', 'SQL'],
            match_score: 0.87,
            skill_match: 0.90,
            salary_match: 0.82,
            location_match: 0.75,
            culture_match: 0.92,
            growth_match: 0.95,
            stability_match: 0.78,
            description: '从事机器学习算法研发，数据分析',
            benefits: ['五险一金', '带薪年假'],
            work_mode: 'onsite',
            company_size: 'startup',
            match_explanation: '您的技术背景适合数据科学岗位，成长空间较大',
            missing_skills: ['Deep Learning', 'Spark'],
            growth_suggestions: ['深入学习深度学习', '掌握大数据处理']
        },
        {
            job_id: '3',
            job_title: 'Full Stack Engineer',
            company: 'StartupTech',
            location: '深圳',
            salary: '18-28万',
            skills: ['JavaScript', 'React', 'Node.js', 'MongoDB'],
            match_score: 0.83,
            skill_match: 0.85,
            salary_match: 0.85,
            location_match: 0.80,
            culture_match: 0.88,
            growth_match: 0.90,
            stability_match: 0.70,
            description: '全栈开发，前后端技术栈，快速迭代',
            benefits: ['期权', '弹性工作'],
            work_mode: 'remote',
            company_size: 'startup',
            match_explanation: '创业公司环境适合快速成长，技术栈匹配度良好',
            missing_skills: ['TypeScript', 'Docker'],
            growth_suggestions: ['学习TypeScript', '掌握容器化部署']
        }
    ];
    
    return mockJobs;
}

function displaySearchResults(results) {
    const resultsContainer = document.getElementById('matchingResults');
    const recommendationsContainer = document.getElementById('jobRecommendations');
    
    // 显示结果区域
    if (resultsContainer) {
        resultsContainer.style.display = 'block';
    }
    
    // 更新统计信息
    updateMatchingStats(results);
    
    // 显示职位卡片
    if (recommendationsContainer) {
        recommendationsContainer.innerHTML = '';
        results.forEach(job => {
            const jobCard = createJobCard(job);
            recommendationsContainer.appendChild(jobCard);
        });
    }
    
    // 显示技能差距分析
    displaySkillGapAnalysis(results);
}

function createJobCard(job) {
    const card = document.createElement('div');
    card.className = 'job-card';
    card.dataset.jobId = job.job_id;
    
    card.innerHTML = `
        <div class="job-header">
            <div class="job-info">
                <h3 class="job-title">${job.job_title}</h3>
                <p class="job-company">${job.company}</p>
            </div>
            <div class="match-score-badge">${Math.round(job.match_score * 100)}%</div>
        </div>
        
        <div class="job-details">
            <div class="detail-item">
                <i class="fas fa-map-marker-alt"></i>
                <span>${job.location}</span>
            </div>
            <div class="detail-item">
                <i class="fas fa-money-bill-wave"></i>
                <span>${job.salary}</span>
            </div>
            <div class="detail-item">
                <i class="fas fa-laptop"></i>
                <span>${getWorkModeText(job.work_mode)}</span>
            </div>
            <div class="detail-item">
                <i class="fas fa-building"></i>
                <span>${getCompanySizeText(job.company_size)}</span>
            </div>
        </div>
        
        <div class="job-tags">
            ${job.skills.map(skill => `<span class="job-tag skill">${skill}</span>`).join('')}
            ${(job.benefits || []).map(benefit => `<span class="job-tag benefit">${benefit}</span>`).join('')}
        </div>
        
        <div class="match-explanation">
            <p><i class="fas fa-lightbulb"></i> ${job.match_explanation}</p>
        </div>
        
        <div class="match-breakdown">
            <div class="breakdown-header">
                <span>匹配度详情</span>
                <button class="breakdown-toggle" onclick="toggleMatchBreakdown('${job.job_id}')">
                    <i class="fas fa-chevron-down"></i> 查看详情
                </button>
            </div>
            <div class="score-bars" id="breakdown-${job.job_id}">
                <div class="score-bar">
                    <div class="score-bar-label">技能匹配</div>
                    <div class="score-bar-fill">
                        <div class="score-bar-progress" style="width: ${job.skill_match * 100}%"></div>
                    </div>
                    <div class="score-bar-value">${Math.round(job.skill_match * 100)}%</div>
                </div>
                <div class="score-bar">
                    <div class="score-bar-label">薪资匹配</div>
                    <div class="score-bar-fill">
                        <div class="score-bar-progress" style="width: ${job.salary_match * 100}%"></div>
                    </div>
                    <div class="score-bar-value">${Math.round(job.salary_match * 100)}%</div>
                </div>
                <div class="score-bar">
                    <div class="score-bar-label">地理位置</div>
                    <div class="score-bar-fill">
                        <div class="score-bar-progress" style="width: ${job.location_match * 100}%"></div>
                    </div>
                    <div class="score-bar-value">${Math.round(job.location_match * 100)}%</div>
                </div>
                <div class="score-bar">
                    <div class="score-bar-label">文化契合</div>
                    <div class="score-bar-fill">
                        <div class="score-bar-progress" style="width: ${job.culture_match * 100}%"></div>
                    </div>
                    <div class="score-bar-value">${Math.round(job.culture_match * 100)}%</div>
                </div>
                <div class="score-bar">
                    <div class="score-bar-label">成长潜力</div>
                    <div class="score-bar-fill">
                        <div class="score-bar-progress" style="width: ${job.growth_match * 100}%"></div>
                    </div>
                    <div class="score-bar-value">${Math.round(job.growth_match * 100)}%</div>
                </div>
                <div class="score-bar">
                    <div class="score-bar-label">工作稳定</div>
                    <div class="score-bar-fill">
                        <div class="score-bar-progress" style="width: ${job.stability_match * 100}%"></div>
                    </div>
                    <div class="score-bar-value">${Math.round(job.stability_match * 100)}%</div>
                </div>
            </div>
        </div>
        
        <div class="job-actions">
            <div class="action-buttons">
                <button class="btn btn-primary btn-sm" onclick="viewJobDetail('${job.job_id}')">
                    <i class="fas fa-eye"></i> 查看详情
                </button>
                <button class="btn btn-outline btn-sm" onclick="addToComparison('${job.job_id}')">
                    <i class="fas fa-balance-scale"></i> 加入对比
                </button>
                <button class="btn btn-outline btn-sm" onclick="saveJob('${job.job_id}')">
                    <i class="fas fa-heart"></i> 收藏
                </button>
                <button class="btn btn-outline btn-sm" onclick="hideJob('${job.job_id}')">
                    <i class="fas fa-eye-slash"></i> 不感兴趣
                </button>
            </div>
            <div class="job-meta">
                发布时间: 3天前 | 查看: 1.2k
            </div>
        </div>
    `;
    
    return card;
}

function getWorkModeText(mode) {
    const modeMap = {
        'remote': '远程工作',
        'hybrid': '混合办公',
        'onsite': '现场办公'
    };
    return modeMap[mode] || '未知';
}

function getCompanySizeText(size) {
    const sizeMap = {
        'startup': '创业公司',
        'small': '小公司',
        'medium': '中等公司',
        'large': '大公司'
    };
    return sizeMap[size] || '未知';
}

function updateMatchingStats(results) {
    const totalMatches = results.length;
    const avgScore = results.reduce((sum, job) => sum + job.match_score, 0) / totalMatches;
    const topMatches = results.filter(job => job.match_score >= 0.8).length;
    const uniqueCompanies = new Set(results.map(job => job.company)).size;
    
    const totalMatchesEl = document.getElementById('totalMatches');
    const avgMatchScoreEl = document.getElementById('avgMatchScore');
    const topMatchesEl = document.getElementById('topMatches');
    const uniqueCompaniesEl = document.getElementById('uniqueCompanies');
    
    if (totalMatchesEl) totalMatchesEl.textContent = totalMatches;
    if (avgMatchScoreEl) avgMatchScoreEl.textContent = Math.round(avgScore * 100) + '%';
    if (topMatchesEl) topMatchesEl.textContent = topMatches;
    if (uniqueCompaniesEl) uniqueCompaniesEl.textContent = uniqueCompanies;
}

function toggleMatchBreakdown(jobId) {
    const breakdownEl = document.getElementById(`breakdown-${jobId}`);
    const toggleBtn = breakdownEl?.parentElement.querySelector('.breakdown-toggle');
    const icon = toggleBtn?.querySelector('i');
    
    if (breakdownEl?.classList.contains('expanded')) {
        breakdownEl.classList.remove('expanded');
        if (icon) icon.className = 'fas fa-chevron-down';
        if (toggleBtn) toggleBtn.innerHTML = '<i class="fas fa-chevron-down"></i> 查看详情';
    } else if (breakdownEl) {
        breakdownEl.classList.add('expanded');
        if (icon) icon.className = 'fas fa-chevron-up';
        if (toggleBtn) toggleBtn.innerHTML = '<i class="fas fa-chevron-up"></i> 收起详情';
    }
}

function displaySkillGapAnalysis(results) {
    const gapAnalysis = document.getElementById('skillGapAnalysis');
    const gapContent = document.getElementById('gapContent');
    
    if (!gapAnalysis || !gapContent) return;
    
    // 收集所有缺失技能
    const allMissingSkills = [];
    const allSuggestions = [];
    
    results.forEach(job => {
        if (job.missing_skills) {
            allMissingSkills.push(...job.missing_skills);
        }
        if (job.growth_suggestions) {
            allSuggestions.push(...job.growth_suggestions);
        }
    });
    
    // 统计技能出现频率
    const skillFreq = {};
    allMissingSkills.forEach(skill => {
        skillFreq[skill] = (skillFreq[skill] || 0) + 1;
    });
    
    // 按频率排序
    const topMissingSkills = Object.entries(skillFreq)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 8);
    
    gapContent.innerHTML = `
        <div class="gap-section">
            <h4><i class="fas fa-exclamation-triangle"></i> 技能缺口分析</h4>
            ${topMissingSkills.map(([skill, freq]) => `
                <div class="skill-gap-item">
                    <span class="skill-name">${skill}</span>
                    <span class="skill-priority ${freq > 2 ? 'high' : freq > 1 ? 'medium' : 'low'}">
                        ${freq > 2 ? '高优先级' : freq > 1 ? '中优先级' : '低优先级'}
                    </span>
                </div>
            `).join('')}
        </div>
        
        <div class="gap-section">
            <h4><i class="fas fa-chart-line"></i> 成长建议</h4>
            ${[...new Set(allSuggestions)].slice(0, 6).map(suggestion => `
                <div class="skill-gap-item">
                    <span class="skill-name">${suggestion}</span>
                    <span class="skill-priority medium">建议学习</span>
                </div>
            `).join('')}
        </div>
    `;
    
    gapAnalysis.style.display = 'block';
}

function addToComparison(jobId) {
    if (comparisonList.includes(jobId)) {
        showNotification('该职位已在对比列表中', 'warning');
        return;
    }
    
    if (comparisonList.length >= 3) {
        showNotification('最多只能对比3个职位', 'warning');
        return;
    }
    
    comparisonList.push(jobId);
    updateComparisonDisplay();
    showNotification('已加入对比列表', 'success');
}

function updateComparisonDisplay() {
    const comparisonArea = document.getElementById('comparisonArea');
    
    if (comparisonArea) {
        if (comparisonList.length > 0) {
            comparisonArea.style.display = 'block';
            generateComparisonTable();
        } else {
            comparisonArea.style.display = 'none';
        }
    }
}

function generateComparisonTable() {
    const comparisonTable = document.getElementById('comparisonTable');
    if (!comparisonTable) return;
    
    comparisonTable.innerHTML = `
        <table>
            <thead>
                <tr>
                    <th>对比项</th>
                    ${comparisonList.map(jobId => `<th>职位 ${jobId}</th>`).join('')}
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>综合匹配度</td>
                    ${comparisonList.map(jobId => `<td>92%</td>`).join('')}
                </tr>
                <tr>
                    <td>薪资水平</td>
                    ${comparisonList.map(jobId => `<td>25-35万</td>`).join('')}
                </tr>
            </tbody>
        </table>
    `;
}

function clearJobComparison() {
    comparisonList = [];
    updateComparisonDisplay();
    showNotification('对比列表已清空', 'info');
}

async function sendMessageToAI() {
    const input = document.getElementById('assistantInput');
    const message = input?.value.trim();
    
    if (!message) return;
    
    addChatMessage(message, 'user');
    if (input) input.value = '';
    
    try {
        const response = await callAIAssistantAPI(message);
        addChatMessage(response, 'assistant');
        
    } catch (error) {
        console.error('AI助手调用失败:', error);
        addChatMessage('抱歉，我暂时无法回应。请稍后再试。', 'assistant');
    }
}

function addChatMessage(message, sender) {
    const chatContainer = document.getElementById('assistantChat');
    if (!chatContainer) return;
    
    const messageEl = document.createElement('div');
    messageEl.className = `chat-message ${sender}-message`;
    
    messageEl.innerHTML = `
        <i class="fas ${sender === 'user' ? 'fa-user' : 'fa-robot'}"></i>
        <div class="message-content">
            <p>${message}</p>
        </div>
    `;
    
    chatContainer.appendChild(messageEl);
    chatContainer.scrollTop = chatContainer.scrollHeight;
}

async function callAIAssistantAPI(message) {
    try {
        const response = await fetch('/api/jh/ai-assistant', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                message: message,
                context: currentSearchConfig
            })
        });
        
        const data = await response.json();
        return data.response || '好的，我来帮您处理这个请求。';
        
    } catch (error) {
        console.error('AI助手API调用失败:', error);
        return '好的，我来帮您处理这个请求。';
    }
}

function showMatchingProgress() {
    const progressContainer = document.getElementById('matchingProgress');
    if (!progressContainer) return;
    
    progressContainer.style.display = 'block';
    
    const steps = progressContainer.querySelectorAll('.step');
    steps.forEach(step => {
        step.classList.remove('active', 'completed');
    });
    
    if (steps[0]) steps[0].classList.add('active');
    
    const progressFill = document.getElementById('progressFill');
    const progressPercent = document.getElementById('progressPercent');
    if (progressFill) progressFill.style.width = '0%';
    if (progressPercent) progressPercent.textContent = '0%';
}

async function updateProgress(stepIndex, message) {
    const steps = document.querySelectorAll('.step');
    const progressFill = document.getElementById('progressFill');
    const progressPercent = document.getElementById('progressPercent');
    
    for (let i = 0; i < stepIndex; i++) {
        if (steps[i]) {
            steps[i].classList.remove('active');
            steps[i].classList.add('completed');
        }
    }
    
    if (steps[stepIndex]) {
        steps[stepIndex].classList.add('active');
    }
    
    const progress = ((stepIndex + 1) / steps.length) * 100;
    if (progressFill) progressFill.style.width = progress + '%';
    if (progressPercent) progressPercent.textContent = Math.round(progress) + '%';
    
    return new Promise(resolve => setTimeout(resolve, 100));
}

function hideMatchingProgress() {
    const progressContainer = document.getElementById('matchingProgress');
    if (progressContainer) {
        progressContainer.style.display = 'none';
    }
}

function handleSortChange() {
    const sortBy = document.getElementById('sortBy')?.value;
    if (currentSearchConfig && currentSearchConfig.results && sortBy) {
        sortSearchResults(currentSearchConfig.results, sortBy);
        displaySearchResults(currentSearchConfig.results);
    }
}

function sortSearchResults(results, sortBy) {
    switch (sortBy) {
        case 'salary':
            results.sort((a, b) => parseSalary(b.salary) - parseSalary(a.salary));
            break;
        case 'growth':
            results.sort((a, b) => b.growth_match - a.growth_match);
            break;
        case 'stability':
            results.sort((a, b) => b.stability_match - a.stability_match);
            break;
        case 'response':
            results.sort((a, b) => Math.random() - 0.5);
            break;
        default:
            results.sort((a, b) => b.match_score - a.match_score);
    }
}

function parseSalary(salaryStr) {
    const match = salaryStr.match(/(\d+)-(\d+)/);
    if (match) {
        return (parseInt(match[1]) + parseInt(match[2])) / 2;
    }
    return 0;
}

function reapplyWeights() {
    if (!currentSearchConfig || !currentSearchConfig.results) return;
    
    currentSearchConfig.results.forEach(job => {
        job.match_score = calculateWeightedScore(job);
    });
    
    const sortBy = document.getElementById('sortBy')?.value || 'overall';
    sortSearchResults(currentSearchConfig.results, sortBy);
    displaySearchResults(currentSearchConfig.results);
}

function calculateWeightedScore(job) {
    const totalWeight = Object.values(matchingWeights).reduce((sum, weight) => sum + weight, 0);
    return (
        job.skill_match * matchingWeights.skill +
        job.salary_match * matchingWeights.salary +
        job.location_match * matchingWeights.location +
        job.culture_match * matchingWeights.culture +
        job.growth_match * matchingWeights.growth +
        job.stability_match * matchingWeights.stability
    ) / totalWeight;
}

function showSubscriptionModal() {
    const modal = document.getElementById('subscriptionModal');
    if (modal) {
        modal.style.display = 'flex';
    }
}

function closeSubscriptionModal() {
    const modal = document.getElementById('subscriptionModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

function resetSearch() {
    const naturalLanguageInput = document.getElementById('naturalLanguageInput');
    const matchingResults = document.getElementById('matchingResults');
    const skillGapAnalysis = document.getElementById('skillGapAnalysis');
    
    if (naturalLanguageInput) naturalLanguageInput.value = '';
    if (matchingResults) matchingResults.style.display = 'none';
    if (skillGapAnalysis) skillGapAnalysis.style.display = 'none';
    
    currentSearchConfig = null;
    comparisonList = [];
    updateComparisonDisplay();
}

function viewJobDetail(jobId) {
    console.log('查看职位详情:', jobId);
    showNotification('正在加载职位详情...', 'info');
}

function saveJob(jobId) {
    console.log('收藏职位:', jobId);
    showNotification('职位已收藏', 'success');
}

function hideJob(jobId) {
    console.log('隐藏职位:', jobId);
    const jobCard = document.querySelector(`[data-job-id="${jobId}"]`);
    if (jobCard) {
        jobCard.style.display = 'none';
        showNotification('职位已隐藏', 'info');
    }
}

function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <i class="fas ${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-triangle' : 'info-circle'}"></i>
        <span>${message}</span>
    `;
    
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#d4edda' : type === 'error' ? '#f8d7da' : type === 'warning' ? '#fff3cd' : '#d1ecf1'};
        color: ${type === 'success' ? '#155724' : type === 'error' ? '#721c24' : type === 'warning' ? '#856404' : '#0c5460'};
        border: 1px solid ${type === 'success' ? '#c3e6cb' : type === 'error' ? '#f5c6cb' : type === 'warning' ? '#ffeaa7' : '#bee5eb'};
        border-radius: 6px;
        padding: 12px 16px;
        z-index: 9999;
        display: flex;
        align-items: center;
        gap: 8px;
        min-width: 250px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        font-size: 14px;
        transition: all 0.3s ease;
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// 智能匹配相关功能
function toggleAdvancedFilters() {
    const content = document.getElementById('advancedFiltersContent');
    const btn = document.getElementById('toggleAdvancedBtn');
    const icon = btn.querySelector('i');
    const span = btn.querySelector('span');
    
    if (content.style.display === 'none') {
        content.style.display = 'block';
        span.textContent = '收起设置';
        icon.className = 'fas fa-chevron-up';
    } else {
        content.style.display = 'none';
        span.textContent = '展开设置';
        icon.className = 'fas fa-chevron-down';
    }
}

// 处理数据源选择
function handleDataSourceChange() {
    const useAnalysisData = document.getElementById('useAnalysisData');
    const useManualData = document.getElementById('useManualData');
    const userProfileSetup = document.getElementById('userProfileSetup');
    const analysisDataStatus = document.getElementById('analysisDataStatus');
    
    // 检查是否有自身分析数据
    const hasAnalysisData = window.lastAnalysisData && Object.keys(window.lastAnalysisData).length > 0;
    
    if (!hasAnalysisData) {
        useAnalysisData.disabled = true;
        useAnalysisData.checked = false;
        analysisDataStatus.textContent = '暂无自身分析数据，请先在"自身分析"标签页完成简历分析';
        analysisDataStatus.style.color = '#ff6b6b';
    } else {
        useAnalysisData.disabled = false;
        analysisDataStatus.textContent = '已有自身分析数据，可用于智能匹配';
        analysisDataStatus.style.color = '#51cf66';
    }
    
    // 显示/隐藏手动输入区域
    if (useManualData.checked && !useAnalysisData.checked) {
        userProfileSetup.style.display = 'block';
    } else {
        userProfileSetup.style.display = 'none';
    }
}

// 权重滑条事件处理
function initializeWeightSliders() {
    const weightSliders = document.querySelectorAll('.weight-slider input[type="range"]');
    weightSliders.forEach(slider => {
        const valueSpan = slider.nextElementSibling;
        
        slider.addEventListener('input', function() {
            const value = this.value * 10;
            valueSpan.textContent = value + '%';
        });
    });
}

// 权重预设处理
function initializeWeightPresets() {
    const presetBtns = document.querySelectorAll('.preset-btn');
    presetBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const preset = this.dataset.preset;
            applyWeightPreset(preset);
            
            // 更新按钮状态
            presetBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
        });
    });
}

// 应用权重预设
function applyWeightPreset(preset) {
    const presets = {
        'balanced': [7, 6, 5, 4, 5, 3],
        'skill-focused': [9, 4, 3, 2, 6, 2],
        'money-focused': [5, 9, 4, 2, 3, 4],
        'growth-focused': [6, 5, 4, 6, 8, 3],
        'stability-focused': [5, 6, 6, 5, 4, 8]
    };
    
    const weights = presets[preset] || presets['balanced'];
    const sliderIds = ['skillWeight', 'salaryWeight', 'locationWeight', 'cultureWeight', 'growthWeight', 'stabilityWeight'];
    
    sliderIds.forEach((id, index) => {
        const slider = document.getElementById(id);
        const valueSpan = slider.nextElementSibling;
        slider.value = weights[index];
        valueSpan.textContent = (weights[index] * 10) + '%';
    });
}

// 自然语言搜索功能
async function handleNaturalLanguageSearch() {
    const searchText = document.getElementById('naturalLanguageInput').value.trim();
    const searchMode = document.querySelector('input[name="searchMode"]:checked').value;
    
    if (!searchText) {
        showNotification('请输入搜索内容', 'warning');
        return;
    }
    
    try {
        // 显示加载状态
        const searchBtn = document.getElementById('nlSearchBtn');
        const originalText = searchBtn.innerHTML;
        searchBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> AI分析中...';
        searchBtn.disabled = true;
        
        // 获取当前筛选条件
        const filters = getCurrentFilters();
        
        // 调用增强的自然语言搜索API
        const results = await callEnhancedNaturalLanguageSearchAPI(searchText, searchMode, filters);
        
        // 显示搜索结果
        displayNaturalLanguageSearchResults(results, searchText, searchMode);
        
        // 恢复按钮状态
        searchBtn.innerHTML = originalText;
        searchBtn.disabled = false;
        
    } catch (error) {
        console.error('自然语言搜索失败:', error);
        showNotification('搜索失败，请稍后重试', 'error');
        
        // 恢复按钮状态
        const searchBtn = document.getElementById('nlSearchBtn');
        searchBtn.innerHTML = '<i class="fas fa-magic"></i> AI智能搜索';
        searchBtn.disabled = false;
    }
}

// 获取当前筛选条件
function getCurrentFilters() {
    return {
        location: getMultiSelectValue('locationFilter'),
        salaryMin: document.getElementById('salaryMin')?.value || '',
        salaryMax: document.getElementById('salaryMax')?.value || '',
        workMode: getCheckboxValues('input[name="workMode"]:checked'),
        companySize: document.getElementById('companySizeFilter')?.value || ''
    };
}

// 获取多选值
function getMultiSelectValue(elementId) {
    const select = document.getElementById(elementId);
    if (!select) return [];
    return Array.from(select.selectedOptions).map(option => option.value);
}

// 获取复选框值
function getCheckboxValues(selector) {
    return Array.from(document.querySelectorAll(selector)).map(cb => cb.value);
}

// 调用增强的自然语言搜索API
async function callEnhancedNaturalLanguageSearchAPI(searchText, searchMode, filters) {
    try {
        const response = await fetch('/api/jh/enhanced-natural-search', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                search_text: searchText,
                search_mode: searchMode,
                filters: filters,
                weights: getCurrentWeights()
            })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        console.warn('API调用失败，使用模拟数据');
        return generateEnhancedMockResults(searchText, searchMode, filters);
    }
}

// 获取当前权重设置
function getCurrentWeights() {
    return {
        skill: document.getElementById('skillWeight')?.value || 7,
        salary: document.getElementById('salaryWeight')?.value || 6,
        location: document.getElementById('locationWeight')?.value || 5,
        culture: document.getElementById('cultureWeight')?.value || 4,
        growth: document.getElementById('growthWeight')?.value || 5,
        stability: document.getElementById('stabilityWeight')?.value || 3
    };
}

// 生成增强的模拟搜索结果
function generateEnhancedMockResults(searchText, searchMode, filters) {
    const keywords = extractKeywords(searchText);
    const baseJobs = [
        {
            title: "Python数据科学家",
            company: "阿里巴巴",
            location: "北京",
            salary: "30-50万",
            type: "全职",
            skills: ["Python", "机器学习", "数据分析", "深度学习"],
            match_score: 92,
            match_reasons: ["技能高度匹配", "薪资符合预期", "公司知名度高"]
        },
        {
            title: "机器学习工程师",
            company: "腾讯",
            location: "深圳",
            salary: "25-40万",
            type: "全职",
            skills: ["Python", "TensorFlow", "机器学习", "算法优化"],
            match_score: 88,
            match_reasons: ["技术栈匹配", "发展前景好", "团队氛围佳"]
        },
        {
            title: "数据分析师",
            company: "字节跳动",
            location: "上海",
            salary: "20-35万",
            type: "全职",
            skills: ["SQL", "Python", "数据可视化", "业务分析"],
            match_score: 85,
            match_reasons: ["工作内容匹配", "成长空间大", "薪资合理"]
        }
    ];
    
    // 根据搜索模式和关键词调整结果
    let results = baseJobs.map(job => {
        let score = job.match_score;
        
        // 基于关键词调整分数
        keywords.forEach(keyword => {
            if (job.title.includes(keyword) || job.skills.some(skill => skill.includes(keyword))) {
                score += 5;
            }
        });
        
        // 基于搜索模式调整
        if (searchMode === 'precise') {
            score = keywords.every(keyword => 
                job.title.includes(keyword) || job.skills.some(skill => skill.includes(keyword))
            ) ? score : score - 20;
        } else if (searchMode === 'ai') {
            score += Math.random() * 10 - 5; // AI模式增加一些随机性
        }
        
        return { ...job, match_score: Math.min(Math.max(score, 60), 98) };
    });
    
    // 按匹配度排序
    results.sort((a, b) => b.match_score - a.match_score);
    
    return {
        jobs: results,
        total_count: results.length,
        search_analysis: {
            extracted_keywords: keywords,
            search_mode: searchMode,
            confidence: 0.85
        }
    };
}

// 提取关键词
function extractKeywords(text) {
    const skillKeywords = ['Python', 'JavaScript', 'Java', 'C++', '机器学习', '数据分析', '人工智能', '深度学习', 'SQL', 'React', 'Vue', 'Node.js'];
    const jobKeywords = ['工程师', '分析师', '科学家', '经理', '主管', '总监', '架构师', '开发'];
    const locationKeywords = ['北京', '上海', '深圳', '杭州', '广州', '成都', '远程', '美国', '加拿大'];
    const companyKeywords = ['阿里', '腾讯', '百度', '字节', '美团', '小米', '华为', '微软', '谷歌'];
    
    const allKeywords = [...skillKeywords, ...jobKeywords, ...locationKeywords, ...companyKeywords];
    const foundKeywords = [];
    
    allKeywords.forEach(keyword => {
        if (text.includes(keyword)) {
            foundKeywords.push(keyword);
        }
    });
    
    return foundKeywords;
}

// 显示自然语言搜索结果
function displayNaturalLanguageSearchResults(results, searchText, searchMode) {
    // 这里可以显示搜索结果，比如在一个模态框或者结果区域
    console.log('搜索结果:', results);
    
    const resultHtml = `
        <div class="search-results-modal">
            <div class="results-header">
                <h3>搜索结果 - ${searchMode === 'precise' ? '精确匹配' : searchMode === 'fuzzy' ? '模糊匹配' : 'AI推荐'}</h3>
                <p>搜索: "${searchText}"</p>
                <p>找到 ${results.total_count} 个匹配职位</p>
            </div>
            <div class="results-list">
                ${results.jobs.map(job => `
                    <div class="job-result-card">
                        <div class="job-header">
                            <h4>${job.title}</h4>
                            <span class="match-score">${job.match_score}% 匹配</span>
                        </div>
                        <div class="job-info">
                            <p><i class="fas fa-building"></i> ${job.company}</p>
                            <p><i class="fas fa-map-marker-alt"></i> ${job.location}</p>
                            <p><i class="fas fa-dollar-sign"></i> ${job.salary}</p>
                        </div>
                        <div class="job-skills">
                            ${job.skills.map(skill => `<span class="skill-tag">${skill}</span>`).join('')}
                        </div>
                        <div class="match-reasons">
                            ${job.match_reasons.map(reason => `<li>${reason}</li>`).join('')}
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>
    `;
    
    // 显示结果（这里简化为console输出，实际应该显示在页面上）
    showNotification(`找到 ${results.total_count} 个匹配职位`, 'success');
}

// 初始化智能匹配功能
function initializeSmartMatching() {
    // 绑定智能匹配按钮事件
    const startMatchingBtn = document.getElementById('startMatchingBtn');
    if (startMatchingBtn) {
        startMatchingBtn.addEventListener('click', handleIntelligentMatching);
    }
    
    // 初始化自身分析数据检测
    const useAnalysisResults = document.getElementById('useAnalysisResults');
    const analysisToggleDescription = document.getElementById('analysisToggleDescription');
    
    if (useAnalysisResults && analysisToggleDescription) {
        checkAnalysisDataAvailability();
        useAnalysisResults.addEventListener('change', updateAnalysisToggleState);
    }
    
    // 初始化具体需求开关
    const useDetailedRequirements = document.getElementById('useDetailedRequirements');
    if (useDetailedRequirements) {
        useDetailedRequirements.addEventListener('change', toggleDetailedRequirements);
    }
}

// 新增：检查自身分析数据可用性
function checkAnalysisDataAvailability() {
    const analysisToggleDescription = document.getElementById('analysisToggleDescription');
    const useAnalysisResults = document.getElementById('useAnalysisResults');
    
    // 检查是否有自身分析数据
    const hasAnalysisData = window.lastAnalysisData && Object.keys(window.lastAnalysisData).length > 0;
    
    if (!hasAnalysisData) {
        useAnalysisResults.disabled = true;
        useAnalysisResults.checked = false;
        analysisToggleDescription.textContent = '暂无自身分析数据，请先完成简历分析后再使用此功能';
        analysisToggleDescription.style.color = 'rgba(255, 255, 255, 0.6)';
    } else {
        useAnalysisResults.disabled = false;
        analysisToggleDescription.textContent = '结合您的简历分析数据进行更精准的职位匹配';
        analysisToggleDescription.style.color = 'rgba(255, 255, 255, 0.8)';
    }
}

// 新增：更新分析数据切换状态
function updateAnalysisToggleState() {
    const useAnalysisResults = document.getElementById('useAnalysisResults');
    const analysisToggleDescription = document.getElementById('analysisToggleDescription');
    
    if (useAnalysisResults.checked) {
        analysisToggleDescription.textContent = '将结合您的简历数据进行匹配，推荐更精准';
    } else {
        analysisToggleDescription.textContent = '仅基于需求描述进行职位匹配';
    }
}

// 新增：获取详细需求表单数据
function getDetailedRequirementsData() {
    const detailedJobTitle = document.getElementById('detailedJobTitle').value.trim();
    const detailedLocation = document.getElementById('detailedLocation').value.trim();
    const detailedSalaryMin = document.getElementById('detailedSalaryMin').value;
    const detailedSalaryMax = document.getElementById('detailedSalaryMax').value;
    const detailedExperience = document.getElementById('detailedExperience').value;
    const detailedSkills = document.getElementById('detailedSkills').value.trim();
    const detailedCompanyType = document.getElementById('detailedCompanyType').value;
    const detailedCompanySize = document.getElementById('detailedCompanySize').value;
    const detailedOtherRequirements = document.getElementById('detailedOtherRequirements').value.trim();
    const useAnalysisResults = document.getElementById('useAnalysisResults');
    
    // 基础验证
    if (!detailedJobTitle && !detailedLocation && !detailedSkills) {
        showNotification('请至少填写期望职位、期望城市或技能要求中的一项', 'warning');
        return null;
    }
    
    // 构造需求描述
    let requirement = '';
    if (detailedJobTitle) requirement += `期望职位：${detailedJobTitle}；`;
    if (detailedLocation) requirement += `期望城市：${detailedLocation}；`;
    if (detailedSalaryMin || detailedSalaryMax) {
        const salaryRange = [];
        if (detailedSalaryMin) salaryRange.push(`${detailedSalaryMin}万以上`);
        if (detailedSalaryMax) salaryRange.push(`${detailedSalaryMax}万以下`);
        requirement += `期望薪资：${salaryRange.join('，')}；`;
    }
    if (detailedExperience) requirement += `工作经验：${detailedExperience}；`;
    if (detailedSkills) requirement += `技能要求：${detailedSkills}；`;
    if (detailedCompanyType) requirement += `公司类型：${detailedCompanyType}；`;
    if (detailedCompanySize) requirement += `公司规模：${detailedCompanySize}；`;
    if (detailedOtherRequirements) requirement += `其他要求：${detailedOtherRequirements}；`;
    
    return {
        requirement: requirement,
        use_analysis_data: useAnalysisResults.checked && !useAnalysisResults.disabled,
        analysis_data: useAnalysisResults.checked ? window.lastAnalysisData : null,
        detailed_data: {
            job_title: detailedJobTitle,
            location: detailedLocation,
            salary_min: detailedSalaryMin,
            salary_max: detailedSalaryMax,
            experience: detailedExperience,
            skills: detailedSkills,
            company_type: detailedCompanyType,
            company_size: detailedCompanySize,
            other_requirements: detailedOtherRequirements
        }
    };
}

// 新增：切换详细需求表单显示
function toggleDetailedRequirements() {
    const useDetailedRequirements = document.getElementById('useDetailedRequirements');
    const detailedRequirementsForm = document.getElementById('detailedRequirementsForm');
    const detailedToggleDescription = document.getElementById('detailedToggleDescription');
    const jobRequirementInput = document.getElementById('jobRequirementInput');
    
    if (useDetailedRequirements.checked) {
        // 显示详细表单
        detailedRequirementsForm.style.display = 'block';
        setTimeout(() => {
            detailedRequirementsForm.classList.add('show');
            // 保持表单内容默认折叠状态，让用户手动展开
        }, 10);
        
        // 禁用文本输入
        jobRequirementInput.disabled = true;
        jobRequirementInput.placeholder = '已启用具体需求匹配，请在下方填写详细信息';
        jobRequirementInput.style.opacity = '0.6';
        
        // 更新描述
        detailedToggleDescription.textContent = '已启用AI智能详细匹配模式，请点击下方表单标题展开填写';
        
        // 平滑滚动到表单
        setTimeout(() => {
            detailedRequirementsForm.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 300);
        
    } else {
        // 隐藏详细表单
        detailedRequirementsForm.classList.remove('show');
        setTimeout(() => {
            detailedRequirementsForm.style.display = 'none';
        }, 300);
        
        // 启用文本输入
        jobRequirementInput.disabled = false;
        jobRequirementInput.placeholder = '请描述您的求职需求，例如：\n• 我想找一份Python开发工作，希望薪资在20-30万\n• 寻找数据分析师岗位，偏好远程工作\n• 期望在互联网公司做产品经理，有发展空间';
        jobRequirementInput.style.opacity = '1';
        
        // 更新描述
        detailedToggleDescription.textContent = '填写详细求职条件，获得更精准的匹配结果';
    }
}

// 新增：切换详细表单的折叠状态
function toggleDetailedForm() {
    const detailedFormContent = document.getElementById('detailedFormContent');
    const detailedFormToggle = document.getElementById('detailedFormToggle');
    
    if (!detailedFormContent || !detailedFormToggle) return;
    
    const isCollapsed = detailedFormContent.classList.contains('collapsed');
    
    if (isCollapsed) {
        // 展开
        detailedFormContent.classList.remove('collapsed');
        detailedFormToggle.classList.remove('collapsed');
        detailedFormToggle.innerHTML = '<i class="fas fa-chevron-down"></i>';
    } else {
        // 折叠
        detailedFormContent.classList.add('collapsed');
        detailedFormToggle.classList.add('collapsed');
        detailedFormToggle.innerHTML = '<i class="fas fa-chevron-up"></i>';
    }
}

// 新增：处理智能匹配请求
async function handleIntelligentMatching() {
    const jobRequirementInput = document.getElementById('jobRequirementInput');
    const useAnalysisResults = document.getElementById('useAnalysisResults');
    const useDetailedRequirements = document.getElementById('useDetailedRequirements');
    const startMatchingBtn = document.getElementById('startMatchingBtn');
    
    let matchingData;
    let apiEndpoint;
    
    if (useDetailedRequirements.checked) {
        // 使用详细需求表单 - 改为使用AI智能匹配
        matchingData = getDetailedRequirementsData();
        if (!matchingData) {
            return; // 验证失败，函数内部已显示错误信息
        }
        // 使用AI智能匹配端点获得更好的分析效果
        apiEndpoint = '/ai-intelligent-matching';
    } else {
        // 使用文本描述 - 默认启用AI智能匹配
        const requirement = jobRequirementInput.value.trim();
        if (!requirement) {
            showNotification('请输入您的求职需求描述', 'warning');
            jobRequirementInput.focus();
            return;
        }
        
        matchingData = {
            requirement: requirement,
            use_analysis_data: useAnalysisResults.checked && !useAnalysisResults.disabled,
            analysis_data: useAnalysisResults.checked ? window.lastAnalysisData : null
        };
        
        // 默认使用AI智能匹配
        apiEndpoint = '/ai-intelligent-matching';
    }
    
    // 显示匹配进度
    showMatchingProgress();
    
    // 更新进度显示为AI匹配步骤
    updateMatchingProgressSteps([
        { id: 'step1', text: 'AI分析需求维度', icon: 'fas fa-brain' },
        { id: 'step2', text: '搜索职位数据', icon: 'fas fa-search' },
        { id: 'step3', text: '多维度智能匹配', icon: 'fas fa-magic' },
        { id: 'step4', text: '生成推荐理由', icon: 'fas fa-lightbulb' }
    ]);
    
    // 禁用按钮
    startMatchingBtn.disabled = true;
    startMatchingBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> AI匹配分析中...';
    
    try {
        // 调用智能匹配API
        const response = await fetch(`${jhDashboard.apiBaseUrl}${apiEndpoint}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(matchingData)
        });
        
        if (!response.ok) {
            throw new Error(`API请求失败: ${response.status}`);
        }
        
        const results = await response.json();
        
        // 显示匹配成功状态
        showMatchingSuccess();
        
        // 延迟显示结果，确保进度条动画完成
        setTimeout(() => {
            // 显示匹配结果
            if (apiEndpoint === '/ai-intelligent-matching') {
                displayAIMatchingResults(results);
            } else {
                displayMatchingResults(results);
            }
            
            showNotification(`AI智能匹配完成，找到 ${results.total_count || 0} 个相关职位`, 'success');
        }, 1500);
        
    } catch (error) {
        console.error('智能匹配失败:', error);
        showNotification('智能匹配失败，请稍后重试', 'error');
        
        // 显示失败状态
        showMatchingFailure();
    } finally {
        // 恢复按钮状态 - 延迟恢复，避免与进度条冲突
        setTimeout(() => {
            startMatchingBtn.disabled = false;
            startMatchingBtn.innerHTML = '<i class="fas fa-magic"></i> 开始AI智能匹配';
        }, 2500);
    }
}

// 新增：显示匹配进度
function showMatchingProgress() {
    const progressElement = document.getElementById('matchingProgress');
    if (progressElement) {
        progressElement.style.display = 'block';
        
        // 模拟进度动画
        const steps = ['step1', 'step2', 'step3', 'step4'];
        const progressFill = document.getElementById('progressFill');
        const progressPercent = document.getElementById('progressPercent');
        
        let currentStep = 0;
        const progressInterval = setInterval(() => {
            if (currentStep < steps.length) {
                // 激活当前步骤
                const stepElement = document.getElementById(steps[currentStep]);
                if (stepElement) {
                    stepElement.classList.add('active');
                }
                
                // 更新进度条
                const progress = ((currentStep + 1) / steps.length) * 100;
                progressFill.style.width = `${progress}%`;
                progressPercent.textContent = `${Math.round(progress)}%`;
                
                currentStep++;
            } else {
                clearInterval(progressInterval);
            }
        }, 800);
        
        // 保存interval ID以便后续清理
        progressElement.progressInterval = progressInterval;
    }
}

// 新增：显示匹配成功状态
function showMatchingSuccess() {
    const progressElement = document.getElementById('matchingProgress');
    if (progressElement) {
        // 清理进度动画
        if (progressElement.progressInterval) {
            clearInterval(progressElement.progressInterval);
            delete progressElement.progressInterval;
        }
        
        // 显示完成状态
        const progressHeader = progressElement.querySelector('.progress-header h4');
        if (progressHeader) {
            progressHeader.innerHTML = '<i class="fas fa-check-circle" style="color: #4CAF50;"></i> AI匹配完成！';
        }
        
        // 设置100%进度
        const progressFill = document.getElementById('progressFill');
        const progressPercent = document.getElementById('progressPercent');
        if (progressFill) progressFill.style.width = '100%';
        if (progressPercent) progressPercent.textContent = '100%';
        
        // 激活所有步骤
        const steps = document.querySelectorAll('.progress-steps .step');
        steps.forEach(step => step.classList.add('active'));
        
        // 标记完成状态，延迟隐藏
        progressElement.setAttribute('data-status', 'completed');
        setTimeout(() => {
            if (progressElement.getAttribute('data-status') === 'completed') {
                hideMatchingProgress();
            }
        }, 3000);
    }
}

// 新增：显示匹配失败状态
function showMatchingFailure() {
    const progressElement = document.getElementById('matchingProgress');
    if (progressElement) {
        // 清理进度动画
        if (progressElement.progressInterval) {
            clearInterval(progressElement.progressInterval);
            delete progressElement.progressInterval;
        }
        
        // 显示失败状态
        const progressHeader = progressElement.querySelector('.progress-header h4');
        if (progressHeader) {
            progressHeader.innerHTML = '<i class="fas fa-exclamation-circle" style="color: #f44336;"></i> AI匹配失败';
        }
        
        // 标记失败状态，延迟隐藏
        progressElement.setAttribute('data-status', 'failed');
        setTimeout(() => {
            if (progressElement.getAttribute('data-status') === 'failed') {
                hideMatchingProgress();
            }
        }, 3000);
    }
}

// 新增：隐藏匹配进度
function hideMatchingProgress() {
    const progressElement = document.getElementById('matchingProgress');
    if (progressElement) {
        // 清理进度动画
        if (progressElement.progressInterval) {
            clearInterval(progressElement.progressInterval);
            delete progressElement.progressInterval;
        }
        
        // 添加淡出动画
        progressElement.style.opacity = '0';
        progressElement.style.transition = 'opacity 0.5s ease';
        
        setTimeout(() => {
            progressElement.style.display = 'none';
            progressElement.style.opacity = '1';
            progressElement.style.transition = '';
            
            // 重置进度状态
            const steps = document.querySelectorAll('.progress-steps .step');
            steps.forEach(step => step.classList.remove('active'));
            const step1 = document.getElementById('step1');
            if (step1) step1.classList.add('active');
            
            const progressFill = document.getElementById('progressFill');
            const progressPercent = document.getElementById('progressPercent');
            const progressHeader = progressElement.querySelector('.progress-header h4');
            
            if (progressFill) progressFill.style.width = '0%';
            if (progressPercent) progressPercent.textContent = '0%';
            if (progressHeader) progressHeader.innerHTML = '<i class="fas fa-brain"></i> AI智能分析中...';
            
            // 清除状态标记
            progressElement.removeAttribute('data-status');
        }, 500);
    }
}

// 新增：显示匹配结果
function displayMatchingResults(results) {
    const matchingResults = document.getElementById('matchingResults');
    if (!matchingResults) return;
    
    // 更新统计信息
    const totalMatches = document.getElementById('totalMatches');
    const avgMatchScore = document.getElementById('avgMatchScore');
    const topMatches = document.getElementById('topMatches');
    const improvementTips = document.getElementById('improvementTips');
    
    if (totalMatches) totalMatches.textContent = results.total_count || 0;
    if (avgMatchScore) avgMatchScore.textContent = `${Math.round(results.avg_score || 0)}%`;
    if (topMatches) topMatches.textContent = results.matches ? results.matches.filter(job => job.match_score >= 80).length : 0;
    if (improvementTips) {
        // 根据匹配情况生成提升建议数量
        const tips = [];
        if (!results.matches || results.matches.length === 0) tips.push('完善简历');
        if (results.avg_score < 60) tips.push('优化技能');
        if (results.matches && results.matches.filter(job => job.match_score >= 80).length === 0) tips.push('扩大搜索范围');
        improvementTips.textContent = tips.length || '0';
    }
    
    // 显示结果区域
    matchingResults.style.display = 'block';
    
    // 平滑滚动到结果区域
    matchingResults.scrollIntoView({ behavior: 'smooth' });
    
    // 如果有匹配结果，显示职位推荐列表
    if (results.matches && results.matches.length > 0) {
        jhDashboard.currentJobs = results.matches;
        displayJobRecommendations(results.matches);
    } else {
        // 没有匹配结果时显示空状态
        displayEmptyMatchingResults();
    }
}

// 显示职位推荐列表（统一现代化设计）
function displayJobRecommendations(jobs) {
    const jobRecommendations = document.getElementById('jobRecommendations');
    if (!jobRecommendations) return;
    
    // 保存推荐职位数据到全局变量，用于详情页面
    if (jobs && Array.isArray(jobs)) {
        window.lastRecommendedPositions = jobs.map((job, index) => ({
            ...job,
            // 确保ID一致性，优先使用原始ID
            id: job.id || job.job_id || index,
            title: job.job_title || job.title,
            company: job.company_name || job.company,
            location: job.job_location || job.location,
            salary_range: job.salary_year_avg || job.salary_range || job.salary,
            posted_at: job.job_posted_date_formatted || job.posted_at || job.job_posted_date || '最近',
            skills: job.job_skills || job.skills_required || job.skills || [],
            match_score: job.match_score || 0,
            reasons: job.match_reasons || job.reasons || [],
            // 保留完整的原始数据供详情页面使用
            originalData: job
        }));
        
        console.log('保存推荐职位数据:', window.lastRecommendedPositions.map(p => ({id: p.id, title: p.title})));
    }
    
    if (!jobs || jobs.length === 0) {
        jobRecommendations.innerHTML = `
            <div class="no-data" style="text-align: center; padding: 3rem; color: var(--text-secondary);">
                <div style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;">🔍</div>
                <h3 style="margin: 0 0 0.5rem; color: var(--text-primary);">暂无匹配职位</h3>
                <p style="margin: 0 0 1.5rem;">我们正在为您寻找最匹配的职位机会</p>
                <div style="margin-top: 1.5rem; padding: 1.5rem; background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%); border-radius: 12px; text-align: left; max-width: 400px; margin: 1.5rem auto 0; border: 1px solid rgba(102, 126, 234, 0.1);">
                    <h4 style="margin: 0 0 1rem; color: var(--text-primary); display: flex; align-items: center; gap: 0.5rem;"><i class="fas fa-lightbulb" style="color: #667eea;"></i> 优化建议</h4>
                    <ul style="margin: 0; padding-left: 1.2rem; line-height: 1.6;">
                        <li>✨ 完善个人简历信息</li>
                        <li>🏷️ 添加更多技能标签</li>
                        <li>💰 调整期望薪资范围</li>
                        <li>📍 扩大工作地点选择</li>
                        <li>🎯 尝试更通用的搜索条件</li>
                    </ul>
                </div>
            </div>
        `;
        return;
    }
    
    // 按匹配度排序
    const sortedJobs = jobs.slice().sort((a, b) => (b.match_score || 0) - (a.match_score || 0));
    
    const formatSalary = (salary) => {
        if (!salary) return '薪资面议';
        if (typeof salary === 'number') return `¥${salary.toLocaleString()}`;
        return salary.includes('面议') ? salary : `¥${salary}`;
    };
    
    const getMatchLevel = (score) => {
        if (score >= 80) return { level: 'high', color: '#48bb78', text: '高度匹配' };
        if (score >= 60) return { level: 'medium', color: '#ed8936', text: '中度匹配' };
        return { level: 'low', color: '#e53e3e', text: '基础匹配' };
    };
    
    jobRecommendations.innerHTML = '<div class="job-cards-grid"></div>';
    const grid = jobRecommendations.querySelector('.job-cards-grid');
    
    sortedJobs.forEach((job, index) => {
        const jobCard = document.createElement('div');
        jobCard.className = 'job-card';
        jobCard.style.animationDelay = `${index * 0.1}s`;
        
        const matchScore = Math.max(0, Math.min(100, job.match_score || 0));
        const matchInfo = getMatchLevel(matchScore);
        // 确保ID与保存到lastRecommendedPositions中的ID一致
        const jobId = job.id || job.job_id || index;
        
        // 生成公司Logo占位符
        const logoPlaceholder = job.company_name ? job.company_name.charAt(0).toUpperCase() : 'C';
        
        // 处理技能标签
        const skills = job.skills_required ? 
            (Array.isArray(job.skills_required) ? job.skills_required : job.skills_required.split(',')) : 
            [];
        
        // 设置匹配等级属性用于CSS样式
        jobCard.setAttribute('data-match-level', matchInfo.level);
        
        // 处理匹配理由，确保有内容显示
        let matchReasons = [];
        if (job.match_reasons && Array.isArray(job.match_reasons)) {
            matchReasons = job.match_reasons.slice(0, 3);
        } else if (job.match_analysis) {
            // 如果有match_analysis，尝试提取关键信息
            matchReasons = [`匹配度: ${matchScore}%`, '技能匹配良好', '地点符合要求'];
        } else {
            // 生成默认的匹配理由
            const reasons = [];
            if (matchScore >= 80) reasons.push('高度匹配您的技能要求');
            if (matchScore >= 60) reasons.push('薪资范围符合预期');
            if (job.job_location) reasons.push(`工作地点匹配: ${job.job_location}`);
            matchReasons = reasons.slice(0, 3);
        }
        
        jobCard.innerHTML = `
            <div class="job-card-header">
                <div class="job-card-title">
                    <h4 title="${jhDashboard.escapeHtml(job.job_title || 'N/A')}">${jhDashboard.escapeHtml(job.job_title || 'N/A')}</h4>
                    <span class="job-badge">${jhDashboard.escapeHtml(job.job_schedule_type || job.employment_type || '全职')}</span>
                </div>
                <div class="job-match" title="${matchInfo.text}" data-level="${matchInfo.level}">
                    <span>${matchScore}</span>
                </div>
            </div>
            
            <div class="job-card-company">
                ${job.company_logo && job.company_logo !== '' ? 
                    `<img class="job-logo" src="${jhDashboard.escapeHtml(job.company_logo)}" alt="${jhDashboard.escapeHtml(job.company_name)} logo" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex'"/>
                     <div class="job-logo" style="display:none;">${logoPlaceholder}</div>` :
                    `<div class="job-logo">${logoPlaceholder}</div>`
                }
                <span title="${jhDashboard.escapeHtml(job.company_name || 'N/A')}">${jhDashboard.escapeHtml(job.company_name || 'N/A')}</span>
            </div>
            
            <div class="job-card-meta">
                <span title="工作地点"><i class="fas fa-map-marker-alt"></i>${jhDashboard.escapeHtml(job.job_location || job.location || '地点待定')}</span>
                <span title="薪资范围"><i class="fas fa-yen-sign"></i>${formatSalary(job.salary_year_avg || job.salary_range || job.salary)}</span>
                <span title="发布时间"><i class="fas fa-clock"></i>${jhDashboard.escapeHtml(job.posted_date || job.post_time || '最近')}</span>
            </div>
            
            ${matchReasons.length > 0 ? `
            <div class="job-card-reasons">
                ${matchReasons.map(reason => `<div class="reason">${jhDashboard.escapeHtml(reason)}</div>`).join('')}
            </div>` : ''}
            
            ${skills.length > 0 ? `
            <div class="job-card-tags">
                ${skills.slice(0, 8).map(skill => {
                    const cleanSkill = skill.trim();
                    return cleanSkill ? `<span class="job-tag" title="${jhDashboard.escapeHtml(cleanSkill)}">${jhDashboard.escapeHtml(cleanSkill)}</span>` : '';
                }).filter(Boolean).join('')}
                ${skills.length > 8 ? `<span class="job-tag" style="background: linear-gradient(135deg, rgba(160, 174, 192, 0.1) 0%, rgba(113, 128, 150, 0.1) 100%); color: #718096; border-color: rgba(113, 128, 150, 0.2);">+${skills.length - 8}</span>` : ''}
            </div>` : ''}
            
            <div class="job-card-actions">
                <button class="btn btn-outline" data-action="compare" data-id="${jobId}" title="添加到对比列表">
                    <i class="fas fa-balance-scale"></i> 对比
                </button>
                <button class="btn btn-secondary" data-action="favorite" data-id="${jobId}" title="收藏此职位">
                    <i class="fas fa-heart"></i> 收藏
                </button>
                <button class="btn btn-primary" onclick="jhDashboard.viewJobDetails('${jobId}', 'recommended_positions')" title="查看完整职位信息">
                    <i class="fas fa-external-link-alt"></i> 详情
                </button>
            </div>
        `;
        
        grid.appendChild(jobCard);
    });
    
    // 添加渐入动画
    jobRecommendations.style.opacity = '0';
    setTimeout(() => {
        jobRecommendations.style.transition = 'opacity 0.5s ease';
        jobRecommendations.style.opacity = '1';
    }, 100);
    
    // 为按钮添加事件监听器
    grid.addEventListener('click', (e) => {
        const button = e.target.closest('button[data-action]');
        if (!button) return;
        
        const action = button.dataset.action;
        const jobId = button.dataset.id;
        
        switch (action) {
            case 'compare':
                handleJobComparison(jobId, button);
                break;
            case 'favorite':
                handleJobFavorite(jobId, button);
                break;
        }
    });
    
    // 添加卡片交互增强
    enhanceJobCardInteractions(jobRecommendations);
}

// 新增：显示空匹配结果状态
function displayEmptyMatchingResults() {
    const jobRecommendations = document.getElementById('jobRecommendations');
    if (!jobRecommendations) return;
    
    jobRecommendations.innerHTML = `
        <div class="empty-results">
            <div class="empty-icon">
                <i class="fas fa-search"></i>
            </div>
            <h3>暂无匹配结果</h3>
            <p>很抱歉，根据您的需求条件暂时没有找到合适的职位。</p>
            <div class="empty-suggestions">
                <h4>建议您：</h4>
                <ul>
                    <li>调整关键词或降低要求条件</li>
                    <li>尝试使用更通用的职位描述</li>
                    <li>考虑扩大地理范围</li>
                </ul>
            </div>
            <button class="btn btn-primary" onclick="document.getElementById('jobRequirementInput').focus()">
                <i class="fas fa-edit"></i> 修改需求
            </button>
        </div>
    `;
}

// 新增：更新匹配进度步骤
function updateMatchingProgressSteps(steps) {
    const progressElement = document.getElementById('matchingProgress');
    if (!progressElement) return;
    
    const stepsContainer = progressElement.querySelector('.progress-steps');
    if (!stepsContainer) return;
    
    // 清空现有步骤
    stepsContainer.innerHTML = '';
    
    // 添加新步骤
    steps.forEach((step, index) => {
        const stepElement = document.createElement('div');
        stepElement.className = 'step';
        stepElement.id = step.id;
        if (index === 0) {
            stepElement.classList.add('active');
        }
        
        stepElement.innerHTML = `
            <i class="${step.icon}"></i>
            <span>${step.text}</span>
        `;
        
        stepsContainer.appendChild(stepElement);
    });
}

// 新增：显示AI匹配结果
function displayAIMatchingResults(results) {
    const resultsContainer = document.getElementById('matchingResults');
    if (!resultsContainer) {
        console.error('Results container not found');
        return;
    }
    
    // 清空之前的结果并重置状态
    resultsContainer.innerHTML = '';
    resultsContainer.style.display = 'none';
    
    if (!results || (!results.matches || results.matches.length === 0)) {
        resultsContainer.innerHTML = `
            <div class="results-header">
                <h3><i class="fas fa-search"></i> AI智能匹配结果</h3>
            </div>
            <div class="no-results">
                <div class="empty-icon">
                    <i class="fas fa-search"></i>
                </div>
                <h3>未找到匹配的职位</h3>
                <p>很抱歉，根据您的需求条件暂时没有找到合适的职位。</p>
                <div class="empty-suggestions">
                    <h4>建议您：</h4>
                    <ul>
                        <li>调整关键词或降低要求条件</li>
                        <li>尝试使用更通用的职位描述</li>
                        <li>考虑扩大地理范围</li>
                    </ul>
                </div>
                <button class="btn btn-primary" onclick="document.getElementById('jobRequirementInput').focus()">
                    <i class="fas fa-edit"></i> 修改需求
                </button>
            </div>
        `;
        resultsContainer.style.display = 'block';
        resultsContainer.scrollIntoView({ behavior: 'smooth' });
        return;
    }
    
    // 创建结果头部
    const headerSection = document.createElement('div');
    headerSection.className = 'results-header';
    headerSection.innerHTML = `
        <h3><i class="fas fa-magic"></i> AI智能匹配结果</h3>
        <div class="results-actions">
            <button class="btn btn-outline btn-sm" id="exportResults">
                <i class="fas fa-download"></i> 导出结果
            </button>
            <button class="btn btn-outline btn-sm" id="newSearch">
                <i class="fas fa-redo"></i> 重新匹配
            </button>
        </div>
    `;
    resultsContainer.appendChild(headerSection);
    
    // 显示需求分析结果
    if (results.requirement_analysis) {
        try {
            const analysisSection = createRequirementAnalysisSection(results.requirement_analysis);
            if (analysisSection) {
                resultsContainer.appendChild(analysisSection);
            }
        } catch (error) {
            console.error('Error creating analysis section:', error);
        }
    }
    
    // 更新页面顶部的统计信息
    const totalMatches = document.getElementById('totalMatches');
    const avgMatchScore = document.getElementById('avgMatchScore');
    const topMatches = document.getElementById('topMatches');
    const improvementTips = document.getElementById('improvementTips');
    
    if (totalMatches) totalMatches.textContent = results.total_count || 0;
    if (avgMatchScore) avgMatchScore.textContent = `${Math.round(results.avg_score || 0)}%`;
    if (topMatches) topMatches.textContent = results.matches ? results.matches.filter(job => job.match_score >= 80).length : 0;
    if (improvementTips) {
        // 根据匹配情况生成提升建议数量
        const tips = [];
        if (!results.matches || results.matches.length === 0) tips.push('完善简历');
        if (results.avg_score < 60) tips.push('优化技能');
        if (results.matches && results.matches.filter(job => job.match_score >= 80).length === 0) tips.push('扩大搜索范围');
        improvementTips.textContent = tips.length || '0';
    }
    
    // 显示匹配统计
    const statsSection = document.createElement('div');
    statsSection.className = 'matching-stats';
    statsSection.innerHTML = `
        <div class="stats-header">
            <h3><i class="fas fa-chart-bar"></i> AI匹配统计</h3>
        </div>
        <div class="stats-content">
            <div class="stat-item">
                <div class="stat-icon">
                    <i class="fas fa-briefcase"></i>
                </div>
                <div class="stat-content">
                    <h4>${results.total_count || 0}</h4>
                    <p>匹配职位</p>
                </div>
            </div>
            <div class="stat-item">
                <div class="stat-icon">
                    <i class="fas fa-percentage"></i>
                </div>
                <div class="stat-content">
                    <h4>${Math.round(results.avg_score || 0)}%</h4>
                    <p>平均匹配度</p>
                </div>
            </div>
            <div class="stat-item">
                <div class="stat-icon">
                    <i class="fas fa-robot"></i>
                </div>
                <div class="stat-content">
                    <h4>AI分析</h4>
                    <p>匹配模式</p>
                </div>
            </div>
        </div>
    `;
    resultsContainer.appendChild(statsSection);
    
    // 显示职位列表 - 使用统一的推荐职位显示组件
    if (results.matches && results.matches.length > 0) {
        const jobsSection = document.createElement('div');
        jobsSection.className = 'jobs-section';
        jobsSection.innerHTML = '<h3><i class="fas fa-briefcase"></i> 推荐职位</h3><div id="jobRecommendations"></div>';
        
        resultsContainer.appendChild(jobsSection);
        
        // 保存数据以供详情页面使用
        jhDashboard.currentJobs = results.matches;
        
        // 使用统一的职位推荐显示函数
        displayJobRecommendations(results.matches);
    }
    
    // 添加事件监听器
    const exportBtn = resultsContainer.querySelector('#exportResults');
    const newSearchBtn = resultsContainer.querySelector('#newSearch');
    
    if (exportBtn) {
        exportBtn.addEventListener('click', () => exportMatchingResults(results));
    }
    
    if (newSearchBtn) {
        newSearchBtn.addEventListener('click', () => {
            resultsContainer.style.display = 'none';
            document.getElementById('jobRequirementInput').focus();
        });
    }
    
    // 显示结果区域并滚动
    resultsContainer.style.display = 'block';
    setTimeout(() => {
        resultsContainer.scrollIntoView({ behavior: 'smooth' });
    }, 100);
}

// 新增：创建需求分析结果展示 - 全面优化版
function createRequirementAnalysisSection(analysis) {
    const section = document.createElement('div');
    section.className = 'requirement-analysis-section';
    
    const analysisItems = [];
    
    // 现代化配色方案 - 采用温暖渐变色系
    const categoryMap = {
        'location_preference': { 
            name: '📍 工作地点偏好', 
            icon: 'fas fa-map-marker-alt', 
            gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            color: '#667eea',
            bgColor: 'rgba(102, 126, 234, 0.1)'
        },
        'skill_requirements': { 
            name: '🔧 技能要求分析', 
            icon: 'fas fa-code', 
            gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
            color: '#f5576c',
            bgColor: 'rgba(245, 87, 108, 0.1)'
        },
        'salary_expectations': { 
            name: '💰 薪资期望范围', 
            icon: 'fas fa-dollar-sign', 
            gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
            color: '#00f2fe',
            bgColor: 'rgba(0, 242, 254, 0.1)'
        },
        'work_style': { 
            name: '🏠 工作方式偏好', 
            icon: 'fas fa-laptop', 
            gradient: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
            color: '#5fb3d4',
            bgColor: 'rgba(168, 237, 234, 0.1)'
        },
        'industry_preference': { 
            name: '🏭 行业领域偏好', 
            icon: 'fas fa-industry', 
            gradient: 'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)',
            color: '#fc8963',
            bgColor: 'rgba(252, 137, 99, 0.1)'
        },
        'career_level': { 
            name: '📈 职业发展层级', 
            icon: 'fas fa-chart-line', 
            gradient: 'linear-gradient(135deg, #a8caba 0%, #5d4e75 100%)',
            color: '#5d4e75',
            bgColor: 'rgba(168, 202, 186, 0.1)'
        },
        'company_culture': { 
            name: '🏢 企业文化偏好', 
            icon: 'fas fa-users', 
            gradient: 'linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%)',
            color: '#a086c9',
            bgColor: 'rgba(251, 194, 235, 0.1)'
        },
        // 新增更多可能的维度
        'experience_level': { 
            name: '⭐ 经验水平要求', 
            icon: 'fas fa-star', 
            gradient: 'linear-gradient(135deg, #fdbb2d 0%, #22c1c3 100%)',
            color: '#22c1c3',
            bgColor: 'rgba(253, 187, 45, 0.1)'
        },
        'education_background': { 
            name: '🎓 教育背景要求', 
            icon: 'fas fa-graduation-cap', 
            gradient: 'linear-gradient(135deg, #ee9ca7 0%, #ffdde1 100%)',
            color: '#ee9ca7',
            bgColor: 'rgba(238, 156, 167, 0.1)'
        },
        'company_size': { 
            name: '🏗️ 公司规模偏好', 
            icon: 'fas fa-building', 
            gradient: 'linear-gradient(135deg, #fad0c4 0%, #ffd1ff 100%)',
            color: '#ff8cc8',
            bgColor: 'rgba(250, 208, 196, 0.1)'
        },
        'benefits_requirements': { 
            name: '🎁 福利待遇要求', 
            icon: 'fas fa-gift', 
            gradient: 'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)',
            color: '#7fb3d3',
            bgColor: 'rgba(161, 196, 253, 0.1)'
        }
    };
    
    // 遍历分析结果 - 更包容的检查逻辑
    Object.entries(analysis).forEach(([key, value]) => {
        if (value && typeof value === 'object') {
            const category = categoryMap[key];
            if (category) {
                // 更灵活地提取数据
                const preference = value.preference || value.description || value.summary || 
                                 (typeof value === 'string' ? value : '未指定具体偏好');
                const importance = value.importance || value.score || value.weight || 5;
                const keywords = value.keywords || value.tags || value.skills || [];
                
                // 即使没有详细信息也要展示
                if (preference !== '未指定具体偏好' || keywords.length > 0 || importance > 0) {
                    analysisItems.push({
                        ...category,
                        preference: preference,
                        importance: Math.min(10, Math.max(1, importance)),
                        keywords: Array.isArray(keywords) ? keywords : [],
                        hasData: !!value.preference || !!value.description
                    });
                }
            }
        }
    });
    
    // 如果没有找到标准维度，尝试展示原始数据
    if (analysisItems.length === 0) {
        Object.entries(analysis).forEach(([key, value]) => {
            if (value && typeof value === 'object') {
                analysisItems.push({
                    name: `📋 ${key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}`,
                    icon: 'fas fa-info-circle',
                    gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                    color: '#667eea',
                    bgColor: 'rgba(102, 126, 234, 0.1)',
                    preference: JSON.stringify(value, null, 2),
                    importance: 5,
                    keywords: [],
                    hasData: true
                });
            }
        });
    }
    
    if (analysisItems.length === 0) {
        section.innerHTML = `
            <div class="analysis-header">
                <h3><i class="fas fa-brain"></i> AI需求分析结果</h3>
                <p class="no-analysis">暂无分析数据，请重新进行需求分析</p>
            </div>
        `;
        return section;
    }
    
    // 按重要度排序
    analysisItems.sort((a, b) => b.importance - a.importance);
    
    section.innerHTML = `
        <div class="analysis-header">
            <h3><i class="fas fa-brain analysis-brain-icon"></i> AI智能需求分析结果</h3>
            <p>🤖 AI深度分析了您的求职需求，共识别出 <strong>${analysisItems.length}</strong> 个关键维度：</p>
            <div class="analysis-summary">
                <span class="summary-badge">总维度: ${analysisItems.length}</span>
                <span class="summary-badge">平均重要度: ${(analysisItems.reduce((sum, item) => sum + item.importance, 0) / analysisItems.length).toFixed(1)}/10</span>
                <span class="summary-badge">关键词总数: ${analysisItems.reduce((sum, item) => sum + item.keywords.length, 0)}</span>
            </div>
        </div>
        <div class="analysis-items">
            ${analysisItems.map((item, index) => `
                <div class="analysis-item modern-card" data-index="${index}" style="--item-gradient: ${item.gradient}; --item-color: ${item.color}; --item-bg: ${item.bgColor}">
                    <div class="item-gradient-bg"></div>
                    <div class="item-header">
                        <div class="icon-container">
                            <i class="${item.icon}"></i>
                        </div>
                        <div class="item-title-group">
                            <span class="item-name">${item.name}</span>
                            <div class="importance-display">
                                <div class="importance-bar">
                                    <div class="importance-fill" style="width: ${item.importance * 10}%"></div>
                                </div>
                                <span class="importance-text">${item.importance}/10</span>
                            </div>
                        </div>
                    </div>
                    <div class="item-content">
                        <div class="preference-text">
                            <i class="fas fa-quote-left quote-icon"></i>
                            <p class="preference">${item.preference}</p>
                        </div>
                        ${item.keywords.length > 0 ? `
                            <div class="keywords-section">
                                <div class="keywords-header">
                                    <i class="fas fa-tags"></i>
                                    <span>关键词标签 (${item.keywords.length})</span>
                                </div>
                                <div class="keywords">
                                    ${item.keywords.map(keyword => 
                                        `<span class="keyword-tag modern-tag">${keyword}</span>`
                                    ).join('')}
                                </div>
                            </div>
                        ` : ''}
                        ${!item.hasData ? `
                            <div class="data-status">
                                <i class="fas fa-exclamation-triangle"></i>
                                <span>数据不完整，建议重新分析</span>
                            </div>
                        ` : ''}
                    </div>
                </div>
            `).join('')}
        </div>
        <div class="analysis-footer">
            <div class="analysis-actions">
                <button class="btn btn-modern" onclick="exportAnalysisData()">
                    <i class="fas fa-download"></i> 导出分析结果
                </button>
                <button class="btn btn-modern-outline" onclick="reanalyzeRequirements()">
                    <i class="fas fa-redo"></i> 重新分析
                </button>
            </div>
            <div class="analysis-tips">
                <i class="fas fa-lightbulb"></i>
                <span>提示：重要度越高的维度在职位匹配中权重越大</span>
            </div>
        </div>
    `;
    
    return section;
}

// 新增：导出分析数据功能
function exportAnalysisData() {
    if (!window.lastAnalysisData) {
        alert('暂无分析数据可导出');
        return;
    }
    
    try {
        const data = JSON.stringify(window.lastAnalysisData, null, 2);
        const blob = new Blob([data], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `需求分析结果_${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        showToast('分析结果已导出！', 'success');
    } catch (error) {
        console.error('导出失败:', error);
        showToast('导出失败，请重试', 'error');
    }
}

// 新增：重新分析需求功能
function reanalyzeRequirements() {
    if (confirm('确定要重新分析需求吗？这将清除当前的分析结果。')) {
        // 清除当前结果
        const resultsContainer = document.getElementById('matchingResults');
        if (resultsContainer) {
            resultsContainer.innerHTML = '';
            resultsContainer.style.display = 'none';
        }
        
        // 重置到输入状态
        const searchSection = document.querySelector('.ai-search-section');
        if (searchSection) {
            const textarea = searchSection.querySelector('textarea');
            if (textarea) {
                textarea.value = '';
                textarea.focus();
            }
        }
        
        showToast('已重置，请重新输入需求', 'info');
    }
}

// 新增：显示提示消息
function showToast(message, type = 'info') {
    // 创建提示元素
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#10b981' : type === 'error' ? '#ef4444' : '#3b82f6'};
        color: white;
        padding: 1rem 1.5rem;
        border-radius: 12px;
        font-weight: 500;
        z-index: 10000;
        animation: toast-slide-in 0.3s ease;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
    `;
    toast.textContent = message;
    
    // 添加动画样式
    const style = document.createElement('style');
    style.textContent = `
        @keyframes toast-slide-in {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        @keyframes toast-slide-out {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }
    `;
    document.head.appendChild(style);
    
    document.body.appendChild(toast);
    
    // 3秒后自动移除
    setTimeout(() => {
        toast.style.animation = 'toast-slide-out 0.3s ease';
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
            if (style.parentNode) {
                style.parentNode.removeChild(style);
            }
        }, 300);
    }, 3000);
}

// 新增：创建AI职位卡片
function createAIJobCard(job, rank) {
    const card = document.createElement('div');
    card.className = 'job-card ai-job-card';
    
    // 构建维度分数显示
    const dimensionScores = job.dimension_scores || {};
    const dimensionDisplay = Object.entries(dimensionScores).map(([dimension, score]) => {
        const dimensionMap = {
            'skills': { name: '技能', icon: 'fas fa-code', color: '#e74c3c' },
            'salary': { name: '薪资', icon: 'fas fa-dollar-sign', color: '#27ae60' },
            'location': { name: '地点', icon: 'fas fa-map-marker-alt', color: '#3498db' },
            'work_style': { name: '工作方式', icon: 'fas fa-laptop', color: '#9b59b6' },
            'industry': { name: '行业', icon: 'fas fa-industry', color: '#f39c12' }
        };
        
        const dim = dimensionMap[dimension] || { name: dimension, icon: 'fas fa-star', color: '#95a5a6' };
        return `
            <div class="dimension-score" title="${dim.name}匹配度: ${score}%">
                <i class="${dim.icon}" style="color: ${dim.color}"></i>
                <span>${score}%</span>
            </div>
        `;
    }).join('');
    
    card.innerHTML = `
        <div class="job-header">
            <div class="job-rank">#${rank}</div>
            <div class="job-title-section">
                <h4 class="job-title">${job.job_title || '未知职位'}</h4>
                <p class="company-name">${job.company_name || '未知公司'}</p>
            </div>
            <div class="match-score-section">
                <div class="overall-score">
                    <span class="score-value">${job.match_score || 0}%</span>
                    <span class="score-label">综合匹配度</span>
                </div>
            </div>
        </div>
        
        <div class="job-details">
            <div class="job-info">
                <span class="job-location"><i class="fas fa-map-marker-alt"></i> ${job.location || '未指定'}</span>
                <span class="job-salary"><i class="fas fa-dollar-sign"></i> ${job.salary || '面议'}</span>
                ${job.job_work_from_home ? '<span class="remote-tag"><i class="fas fa-home"></i> 远程</span>' : ''}
            </div>
            
            ${dimensionDisplay ? `
                <div class="dimension-scores">
                    <div class="scores-header">各维度匹配度：</div>
                    <div class="scores-list">${dimensionDisplay}</div>
                </div>
            ` : ''}
            
            ${job.match_reasons && job.match_reasons.length > 0 ? `
                <div class="match-reasons">
                    <div class="reasons-header"><i class="fas fa-lightbulb"></i> 推荐理由：</div>
                    <ul class="reasons-list">
                        ${job.match_reasons.map(reason => `<li>${reason}</li>`).join('')}
                    </ul>
                </div>
            ` : ''}
            
            ${job.improvement_suggestions && job.improvement_suggestions.length > 0 ? `
                <div class="improvement-suggestions">
                    <div class="suggestions-header"><i class="fas fa-arrow-up"></i> 改进建议：</div>
                    <ul class="suggestions-list">
                        ${job.improvement_suggestions.map(suggestion => `<li>${suggestion}</li>`).join('')}
                    </ul>
                </div>
            ` : ''}
        </div>
        
        <div class="job-actions">
            <button class="btn btn-outline-primary btn-sm" onclick="jhDashboard.viewJobDetails('${job.job_id || job.id || ''}', 'ai_recommendations')">
                <i class="fas fa-eye"></i> 查看详情
            </button>
            <button class="btn btn-primary btn-sm" onclick="applyForJob('${job.job_id || job.id || ''}')">
                <i class="fas fa-paper-plane"></i> 立即申请
            </button>
        </div>
    `;
    
    return card;
}

// 新增：导出匹配结果
function exportMatchingResults(results) {
    if (!results || !results.matches) {
        showNotification('没有可导出的匹配结果', 'warning');
        return;
    }
    
    try {
        // 构建导出内容
        let exportContent = '# AI智能匹配结果报告\n\n';
        exportContent += `生成时间: ${new Date().toLocaleString()}\n\n`;
        
        // 添加需求分析
        if (results.requirement_analysis) {
            exportContent += '## 需求分析结果\n\n';
            Object.entries(results.requirement_analysis).forEach(([key, value]) => {
                if (value && typeof value === 'object' && value.preference) {
                    exportContent += `### ${value.category || key}\n`;
                    exportContent += `- 偏好: ${value.preference}\n`;
                    exportContent += `- 重要度: ${value.importance || 'N/A'}/10\n`;
                    if (value.keywords && value.keywords.length > 0) {
                        exportContent += `- 关键词: ${value.keywords.join(', ')}\n`;
                    }
                    exportContent += '\n';
                }
            });
        }
        
        // 添加匹配统计
        exportContent += '## 匹配统计\n\n';
        exportContent += `- 匹配职位数: ${results.total_count || 0}\n`;
        exportContent += `- 平均匹配度: ${Math.round(results.avg_score || 0)}%\n`;
        exportContent += `- 匹配模式: AI智能分析\n\n`;
        
        // 添加职位列表
        exportContent += '## 推荐职位\n\n';
        results.matches.forEach((job, index) => {
            exportContent += `### ${index + 1}. ${job.job_title || '未知职位'}\n`;
            exportContent += `- 公司: ${job.company_name || '未知公司'}\n`;
            exportContent += `- 地点: ${job.location || '未指定'}\n`;
            exportContent += `- 薪资: ${job.salary || '面议'}\n`;
            exportContent += `- 综合匹配度: ${job.match_score || 0}%\n`;
            
            if (job.dimension_scores) {
                exportContent += '- 各维度匹配度:\n';
                Object.entries(job.dimension_scores).forEach(([dim, score]) => {
                    exportContent += `  - ${dim}: ${score}%\n`;
                });
            }
            
            if (job.match_reasons && job.match_reasons.length > 0) {
                exportContent += '- 推荐理由:\n';
                job.match_reasons.forEach(reason => {
                    exportContent += `  - ${reason}\n`;
                });
            }
            
            if (job.improvement_suggestions && job.improvement_suggestions.length > 0) {
                exportContent += '- 改进建议:\n';
                job.improvement_suggestions.forEach(suggestion => {
                    exportContent += `  - ${suggestion}\n`;
                });
            }
            
            exportContent += '\n';
        });
        
        // 创建并下载文件
        const blob = new Blob([exportContent], { type: 'text/markdown;charset=utf-8' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `AI智能匹配结果_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.md`;
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        
        showNotification('匹配结果已导出', 'success');
        
    } catch (error) {
        console.error('导出失败:', error);
        showNotification('导出失败，请重试', 'error');
    }
}

// 处理职位对比功能
function handleJobComparison(jobId, button) {
    try {
        // 获取或初始化对比列表
        let compareList = JSON.parse(localStorage.getItem('jobCompareList') || '[]');
        
        if (compareList.includes(jobId)) {
            // 如果已在对比列表中，移除它
            compareList = compareList.filter(id => id !== jobId);
            button.innerHTML = '<i class="fas fa-balance-scale"></i> 对比';
            button.classList.remove('active');
            showToast('已从对比列表中移除', 'info');
        } else {
            // 限制对比列表最多5个
            if (compareList.length >= 5) {
                showToast('对比列表最多只能添加5个职位', 'warning');
                return;
            }
            
            // 添加到对比列表
            compareList.push(jobId);
            button.innerHTML = '<i class="fas fa-check"></i> 已添加';
            button.classList.add('active');
            showToast(`已添加到对比列表 (${compareList.length}/5)`, 'success');
        }
        
        // 保存到本地存储
        localStorage.setItem('jobCompareList', JSON.stringify(compareList));
        
        // 更新对比按钮状态
        updateCompareButtonState();
        
    } catch (error) {
        console.error('处理职位对比时出错:', error);
        showToast('操作失败，请重试', 'error');
    }
}

// 处理职位收藏功能
function handleJobFavorite(jobId, button) {
    try {
        // 获取或初始化收藏列表
        let favoriteList = JSON.parse(localStorage.getItem('jobFavoriteList') || '[]');
        
        if (favoriteList.includes(jobId)) {
            // 如果已收藏，取消收藏
            favoriteList = favoriteList.filter(id => id !== jobId);
            button.innerHTML = '<i class="fas fa-heart"></i> 收藏';
            button.classList.remove('favorited');
            showToast('已取消收藏', 'info');
        } else {
            // 添加到收藏列表
            favoriteList.push(jobId);
            button.innerHTML = '<i class="fas fa-heart" style="color: #e53e3e;"></i> 已收藏';
            button.classList.add('favorited');
            showToast('已添加到收藏夹', 'success');
        }
        
        // 保存到本地存储
        localStorage.setItem('jobFavoriteList', JSON.stringify(favoriteList));
        
    } catch (error) {
        console.error('处理职位收藏时出错:', error);
        showToast('操作失败，请重试', 'error');
    }
}

// 更新对比按钮状态
function updateCompareButtonState() {
    const compareList = JSON.parse(localStorage.getItem('jobCompareList') || '[]');
    const compareButtons = document.querySelectorAll('button[data-action="compare"]');
    
    compareButtons.forEach(button => {
        const jobId = button.dataset.id;
        if (compareList.includes(jobId)) {
            button.innerHTML = '<i class="fas fa-check"></i> 已添加';
            button.classList.add('active');
        } else {
            button.innerHTML = '<i class="fas fa-balance-scale"></i> 对比';
            button.classList.remove('active');
        }
    });
}

// 显示提示消息
function showToast(message, type = 'info') {
    // 创建toast元素
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#48bb78' : type === 'warning' ? '#ed8936' : type === 'error' ? '#e53e3e' : '#667eea'};
        color: white;
        padding: 1rem 1.5rem;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        z-index: 10000;
        font-weight: 500;
        max-width: 300px;
        animation: slideInRight 0.3s ease;
    `;
    
    // 添加图标
    const icons = {
        success: '✓',
        warning: '⚠',
        error: '✗',
        info: 'ℹ'
    };
    
    toast.innerHTML = `
        <div style="display: flex; align-items: center; gap: 0.5rem;">
            <span style="font-size: 1.2rem;">${icons[type]}</span>
            <span>${message}</span>
        </div>
    `;
    
    // 添加样式
    if (!document.getElementById('toast-styles')) {
        const style = document.createElement('style');
        style.id = 'toast-styles';
        style.textContent = `
            @keyframes slideInRight {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOutRight {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
    }
    
    document.body.appendChild(toast);
    
    // 3秒后自动移除
    setTimeout(() => {
        toast.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 300);
    }, 3000);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 延迟初始化智能匹配功能，确保页面元素已加载
    setTimeout(initializeSmartMatching, 1000);
    
    // 初始化时更新按钮状态
    setTimeout(updateCompareButtonState, 1500);
});


